<?php

namespace Tests\Feature\Livewire;

use App\Jobs\SyncChannelPostsJob;
use App\Livewire\Onboarding;
use App\Models\Language;
use App\Models\PlatformAccount;
use App\Models\PlatformChannel;
use App\Models\PlatformInstance;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Factory;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;
use Tests\TestCase;

class OnboardingTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        Cache::flush();
        Queue::fake();
        $this->fakeCommunities();
    }

    private function fakeCommunities(): void
    {
        Http::fake(['*/api/v3/community/list*' => Http::response([
            'communities' => [
                ['community' => ['id' => 8, 'name' => 'tech_community', 'title' => 'Tech Community']],
                ['community' => ['id' => 9, 'name' => 'other_community', 'title' => 'Other Community']],
            ],
        ])]);
    }

    private function instanceWithActiveAccount(): PlatformInstance
    {
        $instance = PlatformInstance::factory()->create(['url' => 'https://lemmy.world']);
        PlatformAccount::factory()->create([
            'instance_url' => 'https://lemmy.world',
            'is_active' => true,
        ]);

        return $instance;
    }

    public function test_selecting_an_instance_loads_its_communities(): void
    {
        $instance = $this->instanceWithActiveAccount();

        Livewire::test(Onboarding::class)
            ->set('platformInstanceId', $instance->id)
            ->assertSet('communityLoadError', null)
            ->assertCount('availableCommunities', 2);
    }

    public function test_changing_the_instance_clears_the_previous_selection(): void
    {
        $instance = $this->instanceWithActiveAccount();
        $other = PlatformInstance::factory()->create(['url' => 'https://other.test']);

        Livewire::test(Onboarding::class)
            ->set('platformInstanceId', $instance->id)
            ->set('channelCommunityId', 8)
            ->set('platformInstanceId', $other->id)
            ->assertSet('channelCommunityId', null);
    }

    public function test_unreachable_instance_surfaces_an_error_and_no_communities(): void
    {
        $instance = PlatformInstance::factory()->create(['url' => 'https://unreachable.test']);
        PlatformAccount::factory()->create(['instance_url' => 'https://unreachable.test', 'is_active' => true]);
        Cache::flush();

        // Http::fake() merges stubs, so setUp's success stub would still win —
        // swap the whole fake out instead.
        app()->forgetInstance(Factory::class);
        Http::swap(new Factory);
        Http::fake(['*' => Http::response('nope', 500)]);

        Livewire::test(Onboarding::class)
            ->set('platformInstanceId', $instance->id)
            ->assertSet('availableCommunities', [])
            ->assertNotSet('communityLoadError', null);
    }

    public function test_refresh_communities_refetches_from_the_instance(): void
    {
        $instance = $this->instanceWithActiveAccount();

        Livewire::test(Onboarding::class)
            ->set('platformInstanceId', $instance->id)
            ->call('refreshCommunities')
            ->assertCount('availableCommunities', 2);

        Http::assertSentCount(2);
    }

    public function test_create_channel_requires_a_community(): void
    {
        $instance = $this->instanceWithActiveAccount();
        $language = Language::factory()->create();

        Livewire::test(Onboarding::class)
            ->set('platformInstanceId', $instance->id)
            ->set('channelLanguageId', $language->id)
            ->call('createChannel')
            ->assertHasErrors(['channelCommunityId' => 'required']);

        $this->assertDatabaseCount('platform_channels', 0);
    }

    public function test_create_channel_rejects_a_community_not_on_the_instance(): void
    {
        $instance = $this->instanceWithActiveAccount();
        $language = Language::factory()->create();

        Livewire::test(Onboarding::class)
            ->set('platformInstanceId', $instance->id)
            ->set('channelCommunityId', 4242)
            ->set('channelLanguageId', $language->id)
            ->call('createChannel')
            ->assertHasErrors(['channelCommunityId' => 'in']);

        $this->assertDatabaseCount('platform_channels', 0);
    }

    public function test_create_channel_stores_the_numeric_id_and_the_community_name(): void
    {
        $instance = $this->instanceWithActiveAccount();
        $language = Language::factory()->create();

        Livewire::test(Onboarding::class)
            ->set('platformInstanceId', $instance->id)
            ->set('channelCommunityId', 8)
            ->set('channelLanguageId', $language->id)
            ->set('channelDescription', 'A tech community')
            ->call('createChannel')
            ->assertHasNoErrors();

        $this->assertDatabaseHas('platform_channels', [
            'platform_instance_id' => $instance->id,
            'channel_id' => 8,
            'name' => 'tech_community',
            'description' => 'A tech community',
        ]);
    }

    public function test_create_channel_advances_the_wizard_and_syncs_existing_posts(): void
    {
        $instance = $this->instanceWithActiveAccount();
        $language = Language::factory()->create();

        Livewire::test(Onboarding::class)
            ->set('step', 3)
            ->set('platformInstanceId', $instance->id)
            ->set('channelCommunityId', 8)
            ->set('channelLanguageId', $language->id)
            ->call('createChannel')
            ->assertHasNoErrors()
            ->assertSet('step', 4);

        Queue::assertPushed(SyncChannelPostsJob::class);
    }

    public function test_create_channel_reports_when_the_instance_has_no_active_account(): void
    {
        $instance = PlatformInstance::factory()->create(['url' => 'https://lemmy.world']);
        $language = Language::factory()->create();

        Livewire::test(Onboarding::class)
            ->set('platformInstanceId', $instance->id)
            ->set('channelCommunityId', 8)
            ->set('channelLanguageId', $language->id)
            ->call('createChannel')
            ->assertHasNoErrors()
            ->assertSet('formErrors.general', 'No active platform accounts found for this instance. Please create a platform account first.');

        $this->assertDatabaseCount('platform_channels', 0);
    }

    public function test_mount_prefills_the_community_select_from_an_existing_channel(): void
    {
        $instance = $this->instanceWithActiveAccount();
        PlatformChannel::factory()->create([
            'platform_instance_id' => $instance->id,
            'channel_id' => 8,
            'name' => 'tech_community',
            'is_active' => true,
        ]);

        Livewire::test(Onboarding::class)
            ->assertSet('platformInstanceId', $instance->id)
            ->assertSet('channelCommunityId', 8)
            ->assertCount('availableCommunities', 2);
    }
}
