<?php

namespace Tests\Feature;

use App\Campaigns\Manager\PlatformEntity;
use App\Campaigns\Manager\PlatformSnapshot;
use App\Campaigns\Manager\Readers\MetaStructureReader;
use App\Campaigns\Manager\StructureReader;
use App\Livewire\CampaignManager\EditEntity;
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 Livewire\Livewire;
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();

        $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: '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'));
    }

    public function test_committed_rollout_is_meta_only_even_with_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,linkedin,google';
        }

        try {
            $settings = require config_path('campaign-manager.php');
            $this->assertSame(['meta'], $settings['visible_platforms']);
            $this->assertSame(['meta'], $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_hidden_platforms_can_be_restored_without_changing_their_readers(): void
    {
        config(['campaign-manager.visible_platforms' => ['meta', 'google', 'linkedin']]);
        $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('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');
    }
}
