<?php

namespace Tests\Feature;

use App\Agent\Workspace;
use App\Campaigns\Manager\PlatformEntity;
use App\Campaigns\Manager\PlatformSnapshot;
use App\Campaigns\Manager\Readers\GoogleStructureReader;
use App\Campaigns\Manager\Readers\LinkedInStructureReader;
use App\Campaigns\Manager\Readers\MetaStructureReader;
use App\Campaigns\Manager\StructureReader;
use App\Livewire\CampaignManager\EditEntity;
use App\Livewire\CampaignManager\Index;
use App\Livewire\CampaignManager\Show;
use App\Models\Campaign;
use App\Models\CampaignPlatformDrift;
use App\Models\CampaignPlatformEntity;
use App\Models\CampaignSyncRun;
use App\Models\User;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Laravel\Ai\Models\Conversation;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Tests\TestCase;

/**
 * A buyer sees their own published campaigns, opens one, and gets the platform's
 * current structure - read on open when stale, and on demand within a limit.
 */
class CampaignManagerPagesTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    protected function setUp(): void
    {
        parent::setUp();

        $this->user = User::factory()->create();

        foreach ([MetaStructureReader::class, GoogleStructureReader::class, LinkedInStructureReader::class] as $reader) {
            $this->app->bind($reader, fn (): StructureReader => new class implements StructureReader
            {
                public function read(Campaign $campaign, ?string $actor = null): PlatformSnapshot
                {
                    return new PlatformSnapshot([
                        new PlatformEntity(type: 'campaign', externalId: (string) $campaign->external_campaign_id, name: 'Winter Sale', status: 'ACTIVE'),
                        new PlatformEntity(type: 'ad_set', externalId: 'adset-1', parentType: 'campaign', parentExternalId: (string) $campaign->external_campaign_id, name: 'US mobile', status: 'ACTIVE', settings: ['daily_budget' => 25.0]),
                    ]);
                }
            });
        }
    }

    private function campaign(User $owner, array $attributes = []): Campaign
    {
        return Campaign::create([
            'user_id' => $owner->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'external_campaign_id' => '120252047635070626',
            ...$attributes,
        ]);
    }

    public function test_the_index_lists_only_my_published_campaigns_on_supported_platforms(): void
    {
        $this->campaign($this->user, ['name' => 'Mine on Meta']);
        $this->campaign($this->user, ['name' => 'My draft', 'status' => 'draft', 'external_campaign_id' => null]);
        $this->campaign($this->user, ['name' => 'Mine on TikTok', 'platform' => 'tiktok']);
        $this->campaign(User::factory()->create(), ['name' => 'Someone else']);

        $this->actingAs($this->user)
            ->get(route('campaign-manager.index'))
            ->assertOk()
            ->assertSee('Meta optimization goals remain read-only after launch.')
            ->assertSee('Mine on Meta')
            ->assertDontSee('My draft')
            ->assertDontSee('Mine on TikTok')
            ->assertDontSee('Someone else');
    }

    public function test_guests_are_sent_to_login(): void
    {
        $this->get(route('campaign-manager.index'))->assertRedirect(route('login'));
    }

    /** @return array<string, array{string}> */
    public static function chatPlatforms(): array
    {
        return [
            'Meta' => ['meta'],
            'Google' => ['google'],
            'LinkedIn' => ['linkedin'],
        ];
    }

    #[DataProvider('chatPlatforms')]
    public function test_opening_a_campaign_creates_a_focused_chat_instead_of_linking_to_the_manager_editor(string $platform): void
    {
        $campaign = $this->campaign($this->user, ['platform' => $platform]);

        $this->actingAs($this->user)->get(route('campaign-manager.index'))
            ->assertOk()
            ->assertSee('openChat('.$campaign->id.')', false)
            ->assertDontSee('href="'.route('campaign-manager.show', $campaign).'"', false);

        $component = Livewire::actingAs($this->user)->test(Index::class)->call('openChat', $campaign->id);
        $conversation = Conversation::query()->sole();

        $component->assertRedirect(route('chat.show', ['conversation' => $conversation->id]));
        $this->assertSame((string) $this->user->id, (string) $conversation->participant_id);
        $workspace = new Workspace($conversation->id);
        $this->assertTrue($campaign->is($workspace->focus()));
        $this->assertCount(1, $workspace->artifacts(Campaign::class));
        $this->assertDatabaseCount('campaign_changes', 0);
        $this->assertSame(CampaignSyncRun::Succeeded, $campaign->latestSyncRun()->first()->status);
        $this->assertSame(2, $campaign->platformEntities()->count());

        $this->get(route('chat.show', ['conversation' => $conversation->id]))
            ->assertOk()
            ->assertViewHas('hasCampaign', true);

        Livewire::actingAs($this->user)->test(Index::class)->call('openChat', $campaign->id)
            ->assertRedirect(route('chat.show', ['conversation' => $conversation->id]));
        $this->assertSame(1, Conversation::query()->count());
        $this->assertSame(2, $campaign->syncRuns()->count());
    }

    public function test_opening_chat_updates_the_manager_snapshot_and_drift_without_overwriting_local_edits(): void
    {
        $campaign = $this->campaign($this->user, ['name' => 'My pending name']);
        CampaignSyncRun::factory()->for($campaign)->create(['platform' => 'meta']);
        $entity = CampaignPlatformEntity::factory()->for($campaign)->create([
            'entity_type' => 'campaign',
            'external_id' => $campaign->external_campaign_id,
            'name' => 'Old platform name',
            'status' => 'PAUSED',
        ]);

        Livewire::actingAs($this->user)->test(Index::class)->call('openChat', $campaign->id);

        $this->assertSame('Winter Sale', $entity->fresh()->name);
        $this->assertSame('ACTIVE', $entity->fresh()->status);
        $this->assertTrue($campaign->platformDrifts()->where('field', 'name')->exists());
        $this->assertSame('My pending name', $campaign->fresh()->name);
        $this->actingAs($this->user)->get(route('campaign-manager.index'))
            ->assertOk()
            ->assertSee('>Winter Sale</button>', false)
            ->assertDontSee('>My pending name</button>', false);
    }

    public function test_a_failed_platform_read_preserves_the_snapshot_and_does_not_open_chat(): void
    {
        $campaign = $this->campaign($this->user);
        $entity = CampaignPlatformEntity::factory()->for($campaign)->create(['name' => 'Last known name']);
        $this->app->bind(MetaStructureReader::class, fn (): StructureReader => new class implements StructureReader
        {
            public function read(Campaign $campaign, ?string $actor = null): PlatformSnapshot
            {
                throw new RuntimeException('Platform unavailable');
            }
        });

        Livewire::actingAs($this->user)->test(Index::class)->call('openChat', $campaign->id)
            ->assertNoRedirect()
            ->assertSee('Platform unavailable');

        $this->assertSame('Last known name', $entity->fresh()->name);
        $this->assertSame(CampaignSyncRun::Failed, $campaign->latestSyncRun()->first()->status);
        $this->assertSame(0, Conversation::query()->count());
    }

    public function test_partial_platform_reads_update_the_manager_and_warn_in_chat(): void
    {
        $campaign = $this->campaign($this->user);
        $this->app->bind(MetaStructureReader::class, fn (): StructureReader => new class implements StructureReader
        {
            public function read(Campaign $campaign, ?string $actor = null): PlatformSnapshot
            {
                return new PlatformSnapshot([
                    new PlatformEntity(type: 'campaign', externalId: (string) $campaign->external_campaign_id, name: 'Read just now', status: 'PAUSED'),
                ], ['ad'], ['Ads could not be fully read.']);
            }
        });

        Livewire::actingAs($this->user)->test(Index::class)->call('openChat', $campaign->id);

        $conversation = Conversation::query()->sole();
        $this->assertSame(CampaignSyncRun::Partial, $campaign->latestSyncRun()->first()->status);
        $this->get(route('chat.show', ['conversation' => $conversation->id]))
            ->assertOk()
            ->assertSee('The platform read was incomplete.')
            ->assertSee('Ads could not be fully read.');
    }

    public function test_opening_chat_rate_limits_platform_refreshes(): void
    {
        config(['campaign-manager.refreshes_per_minute' => 1]);
        $campaign = $this->campaign($this->user);
        $component = Livewire::actingAs($this->user)->test(Index::class)->call('openChat', $campaign->id);

        $component->call('openChat', $campaign->id)
            ->assertSee('Refreshed too often.');

        $this->assertSame(1, $campaign->syncRuns()->count());
    }

    public function test_opening_a_shared_campaign_does_not_reuse_someone_elses_private_chat(): void
    {
        $campaign = $this->campaign($this->user);
        $other = User::factory()->create();
        $conversation = Conversation::query()->create([
            'id' => (string) Str::uuid7(),
            'title' => 'Private campaign chat',
            'participant_type' => $other->getMorphClass(),
            'participant_id' => $other->id,
        ]);
        $workspace = new Workspace($conversation->id);
        $workspace->ownedBy($other);
        $workspace->produced($campaign);

        Livewire::actingAs($this->user)->test(Index::class)->call('openChat', $campaign->id);

        $mine = Conversation::query()->where('participant_id', $this->user->id)->sole();
        $this->assertNotSame($conversation->id, $mine->id);
        $this->assertSame((string) $other->id, (string) $conversation->fresh()->participant_id);
        $this->assertTrue($campaign->is((new Workspace($mine->id))->focus()));
    }

    public function test_opening_an_inaccessible_or_hidden_campaign_cannot_create_a_chat(): void
    {
        $otherCampaign = $this->campaign(User::factory()->create());
        $hidden = $this->campaign($this->user, ['platform' => 'google']);
        config(['campaign-manager.visible_platforms' => ['meta']]);

        foreach ([$otherCampaign, $hidden] as $campaign) {
            try {
                Livewire::actingAs($this->user)->test(Index::class)->call('openChat', $campaign->id);
                $this->fail('An inaccessible campaign was opened in chat.');
            } catch (ModelNotFoundException $exception) {
                $this->assertSame(Campaign::class, $exception->getModel());
            }
        }

        $this->assertSame(0, Conversation::query()->count());
    }

    public function test_committed_rollout_is_not_changed_by_environment_overrides(): void
    {
        $keys = ['CAMPAIGN_MANAGER_VISIBLE_PLATFORMS', 'CAMPAIGN_MANAGER_EDIT_PLATFORMS'];
        $previous = [];
        foreach ($keys as $key) {
            $previous[$key] = $_ENV[$key] ?? null;
            $_ENV[$key] = 'meta';
        }

        try {
            $settings = require config_path('campaign-manager.php');
            $this->assertSame(['meta', 'linkedin', 'google'], $settings['visible_platforms']);
            $this->assertSame(['meta', 'linkedin', 'google'], $settings['edit_platforms']);
        } finally {
            foreach ($keys as $key) {
                if ($previous[$key] === null) {
                    unset($_ENV[$key]);
                } else {
                    $_ENV[$key] = $previous[$key];
                }
            }
        }
    }

    public function test_meta_only_rollout_hides_other_platforms_and_blocks_direct_access(): void
    {
        config(['campaign-manager.visible_platforms' => ['meta']]);
        $this->campaign($this->user, ['name' => 'Visible Meta campaign']);
        $google = $this->campaign($this->user, ['name' => 'Hidden Google campaign', 'platform' => 'google']);
        $linkedIn = $this->campaign($this->user, ['name' => 'Hidden LinkedIn campaign', 'platform' => 'linkedin']);

        foreach (['', '?platform=google', '?platform=linkedin'] as $filter) {
            $this->actingAs($this->user)->get(route('campaign-manager.index').$filter)
                ->assertOk()
                ->assertSee('Visible Meta campaign')
                ->assertDontSee('Hidden Google campaign')
                ->assertDontSee('Hidden LinkedIn campaign')
                ->assertDontSee('Google Ads')
                ->assertDontSee('LinkedIn');
        }

        foreach ([$google, $linkedIn] as $campaign) {
            $this->get(route('campaign-manager.show', $campaign))->assertNotFound();
            $entity = CampaignPlatformEntity::factory()->for($campaign)->create(['platform' => $campaign->platform]);
            try {
                app(EditEntity::class)->mount($campaign, $entity);
                $this->fail('A hidden platform was accessible through the edit component.');
            } catch (ModelNotFoundException $exception) {
                $this->assertSame(Campaign::class, $exception->getModel());
            }
            $this->assertSame(0, $campaign->syncRuns()->count());
        }
    }

    public function test_the_default_rollout_shows_all_supported_platforms(): void
    {
        $this->campaign($this->user, ['name' => 'Meta campaign']);
        $this->campaign($this->user, ['name' => 'Google campaign', 'platform' => 'google']);
        $this->campaign($this->user, ['name' => 'LinkedIn campaign', 'platform' => 'linkedin']);

        $this->actingAs($this->user)->get(route('campaign-manager.index'))
            ->assertOk()
            ->assertSee('Meta campaign')
            ->assertSee('Google campaign')
            ->assertSee('LinkedIn campaign');
    }

    public function test_another_users_campaign_is_not_found(): void
    {
        $theirs = $this->campaign(User::factory()->create());

        $this->actingAs($this->user)
            ->get(route('campaign-manager.show', $theirs))
            ->assertNotFound();
    }

    public function test_opening_a_never_read_campaign_reads_it(): void
    {
        $campaign = $this->campaign($this->user);

        $this->actingAs($this->user)->get(route('campaign-manager.show', $campaign))->assertOk();

        Livewire::actingAs($this->user)
            ->test(Show::class, ['campaign' => $campaign])
            ->call('refreshIfStale')
            ->assertSet('problem', null)
            ->assertSee('US mobile');

        $this->assertSame('open', $campaign->latestSyncRun()->first()->trigger);
    }

    public function test_opening_a_freshly_read_campaign_does_not_read_again(): void
    {
        $campaign = $this->campaign($this->user);
        CampaignSyncRun::factory()->for($campaign)->create(['platform' => 'meta']);

        Livewire::actingAs($this->user)
            ->test(Show::class, ['campaign' => $campaign])
            ->call('refreshIfStale');

        $this->assertSame(1, $campaign->syncRuns()->count());
    }

    public function test_manual_refresh_is_rate_limited(): void
    {
        config(['campaign-manager.refreshes_per_minute' => 1]);
        $campaign = $this->campaign($this->user);

        $component = Livewire::actingAs($this->user)
            ->test(Show::class, ['campaign' => $campaign])
            ->call('refresh')
            ->assertSet('problem', null)
            ->call('refresh');

        $this->assertStringContainsString('Refreshed too often', (string) $component->get('problem'));
        $this->assertSame(1, $campaign->syncRuns()->count());
    }

    public function test_the_page_shows_what_changed_on_the_platform_and_failed_reads(): void
    {
        $campaign = $this->campaign($this->user);
        $run = CampaignSyncRun::factory()->for($campaign)->create(['platform' => 'meta', 'drift_count' => 2]);
        CampaignSyncRun::factory()->for($campaign)->failed('Meta was unreachable')->create(['platform' => 'meta']);
        $adSet = CampaignPlatformEntity::factory()->for($campaign)->create(['name' => 'US mobile', 'settings' => ['daily_budget' => 30, 'targeting' => ['geo_locations' => ['countries' => ['US', 'CA']]]]]);
        CampaignPlatformDrift::create(['campaign_id' => $campaign->id, 'campaign_sync_run_id' => $run->id, 'campaign_platform_entity_id' => $adSet->id, 'kind' => CampaignPlatformDrift::Changed, 'field' => 'settings.daily_budget', 'before' => 25, 'after' => 30, 'detected_at' => now()]);
        CampaignPlatformDrift::create(['campaign_id' => $campaign->id, 'campaign_sync_run_id' => $run->id, 'campaign_platform_entity_id' => $adSet->id, 'kind' => CampaignPlatformDrift::Changed, 'field' => 'settings.targeting', 'before' => ['geo_locations' => ['countries' => ['US']]], 'after' => ['geo_locations' => ['countries' => ['US', 'CA']]], 'detected_at' => now()]);

        $this->actingAs($this->user)
            ->get(route('campaign-manager.show', $campaign))
            ->assertOk()
            ->assertSee('US mobile')
            ->assertSee('Meta was unreachable')
            ->assertSee('25')
            ->assertSee('30');
    }
}
