<?php

namespace Tests\Feature;

use App\Campaigns\Manager\CampaignSynchronizer;
use App\Campaigns\Manager\Editing\EditRefused;
use App\Campaigns\Manager\Editing\EntityEditor;
use App\Livewire\CampaignManager\EditEntity;
use App\Models\Campaign;
use App\Models\CampaignChange;
use App\Models\CampaignEntityEdit;
use App\Models\CampaignPlatformEntity;
use App\Models\User;
use App\Services\GoogleAdsService;
use App\Services\LinkedIn\LinkedIn;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
use Livewire\Livewire;
use Mockery;
use Tests\TestCase;

/**
 * Renaming a platform object from the campaign manager.
 *
 * The platform is re-read before anything is sent and once after, so a change
 * made in Ads Manager in the meantime stops the edit, and an edit is only
 * called done when the platform reports the new value.
 */
class CampaignManagerEditTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    /** @var array{campaign: array<string, mixed>, adsets: list<array<string, mixed>>, ads: list<array<string, mixed>>, refuse: bool, ignore: bool} */
    private array $meta = ['campaign' => [], 'adsets' => [], 'ads' => [], 'refuse' => false, 'ignore' => false];

    /** @var list<array{id: string, fields: array<string, mixed>}> */
    private array $writes = [];

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

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*', 'google:*', 'linkedin:*'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 50,
            'campaign-manager.edit_platforms' => ['meta', 'google', 'linkedin'],
            'campaign-manager.edit_categories' => ['name'],
        ]);

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

        $this->meta['campaign'] = [
            'id' => '120252047635070626', 'name' => 'Winter Sale', 'status' => 'ACTIVE',
            'effective_status' => 'ACTIVE', 'objective' => 'OUTCOME_TRAFFIC', 'account_id' => '111',
        ];
        $this->meta['adsets'] = [
            ['id' => '2001', 'name' => 'US mobile', 'status' => 'ACTIVE', 'daily_budget' => '2500'],
        ];
        $this->meta['ads'] = [
            ['id' => '3001', 'name' => 'Ad 1', 'status' => 'ACTIVE', 'effective_status' => 'ACTIVE', 'adset_id' => '2001'],
        ];

        Http::fake(function (Request $request) {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            if ($request->method() === 'POST') {
                $id = basename($path);
                $fields = array_diff_key($request->data(), ['access_token' => true]);
                $this->writes[] = ['id' => $id, 'fields' => $fields];

                if ($this->meta['refuse']) {
                    return Http::response(['error' => ['message' => 'Invalid parameter', 'code' => 100]], 400);
                }

                if (! $this->meta['ignore']) {
                    $this->rename($id, (string) $fields['name']);
                }

                return Http::response(['success' => true]);
            }

            return match (true) {
                str_ends_with($path, '/adsets') => Http::response(['data' => $this->meta['adsets']]),
                str_ends_with($path, '/ads') => Http::response(['data' => $this->meta['ads']]),
                default => Http::response($this->meta['campaign']),
            };
        });
    }

    private function rename(string $id, string $name): void
    {
        if ($id === $this->meta['campaign']['id']) {
            $this->meta['campaign']['name'] = $name;
        }

        foreach (['adsets', 'ads'] as $edge) {
            foreach ($this->meta[$edge] as $i => $row) {
                if ($row['id'] === $id) {
                    $this->meta[$edge][$i]['name'] = $name;
                }
            }
        }
    }

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

    /** A campaign read once, so the manager has a snapshot to edit from. */
    private function read(?Campaign $campaign = null): Campaign
    {
        $campaign ??= $this->campaign();
        app(CampaignSynchronizer::class)->sync($campaign);

        return $campaign;
    }

    private function entity(Campaign $campaign, string $externalId): CampaignPlatformEntity
    {
        return $campaign->platformEntities()->where('external_id', $externalId)->sole();
    }

    private function editor(): EntityEditor
    {
        return app(EntityEditor::class);
    }

    // ------------------------------------------------------------------ Meta

    public function test_an_ad_set_is_renamed_and_confirmed_by_reading_it_back(): void
    {
        $campaign = $this->read();
        $adSet = $this->entity($campaign, '2001');

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, ['name' => '  US mobile - spring  ']);
        $this->assertSame(['name' => ['before' => 'US mobile', 'after' => 'US mobile - spring']], $edit->changes);
        $this->assertSame([], $this->writes);

        $edit = $this->editor()->apply($edit, $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertNotNull($edit->verified_at);
        $this->assertSame(['name' => 'US mobile - spring'], $edit->readback);
        $this->assertSame([['id' => '2001', 'fields' => ['name' => 'US mobile - spring']]], $this->writes);
        $this->assertSame('US mobile - spring', $adSet->refresh()->name);

        $change = CampaignChange::sole();
        $this->assertSame('applied', $change->state);
        $this->assertSame(['ad_set:2001' => ['name' => 'US mobile - spring']], $change->changes);
        $this->assertSame($change->id, $edit->campaign_change_id);
        $this->assertSame(['manual', 'pre_apply', 'readback'], $campaign->syncRuns()->orderBy('id')->pluck('trigger')->all());
    }

    public function test_a_change_made_in_ads_manager_after_proposing_stops_the_edit(): void
    {
        $campaign = $this->read();
        $edit = $this->editor()->propose($campaign, $this->entity($campaign, '2001'), $this->user, ['name' => 'Renamed']);

        $this->meta['adsets'][0]['daily_budget'] = '4000';
        $edit = $this->editor()->apply($edit, $this->user);

        $this->assertSame(CampaignEntityEdit::Stale, $edit->state);
        $this->assertStringContainsString('daily_budget', (string) $edit->error);
        $this->assertSame([], $this->writes);
        $this->assertSame(0, CampaignChange::count());
    }

    public function test_an_object_deleted_on_the_platform_is_not_written_to(): void
    {
        $campaign = $this->read();
        $edit = $this->editor()->propose($campaign, $this->entity($campaign, '3001'), $this->user, ['name' => 'Renamed']);

        $this->meta['ads'] = [];
        $edit = $this->editor()->apply($edit, $this->user);

        $this->assertSame(CampaignEntityEdit::Stale, $edit->state);
        $this->assertSame([], $this->writes);
    }

    public function test_a_refusal_from_the_platform_is_recorded_and_nothing_is_claimed(): void
    {
        $campaign = $this->read();
        $edit = $this->editor()->propose($campaign, $this->entity($campaign, '2001'), $this->user, ['name' => 'Renamed']);

        $this->meta['refuse'] = true;
        $edit = $this->editor()->apply($edit, $this->user);

        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('refused', (string) $edit->error);
        $this->assertSame('failed', CampaignChange::sole()->state);
        $this->assertSame('US mobile', $this->entity($campaign, '2001')->name);
    }

    public function test_an_accepted_change_that_does_not_read_back_is_unconfirmed(): void
    {
        $campaign = $this->read();
        $edit = $this->editor()->propose($campaign, $this->entity($campaign, '2001'), $this->user, ['name' => 'Renamed']);

        $this->meta['ignore'] = true;
        $edit = $this->editor()->apply($edit, $this->user);

        $this->assertSame(CampaignEntityEdit::Unconfirmed, $edit->state);
        $this->assertNull($edit->verified_at);
        $this->assertSame(['name' => 'US mobile'], $edit->readback);
    }

    public function test_the_kill_switch_keeps_the_proposal_open_and_sends_nothing(): void
    {
        $campaign = $this->read();
        $edit = $this->editor()->propose($campaign, $this->entity($campaign, '2001'), $this->user, ['name' => 'Renamed']);
        config(['platforms.guardrails.paused' => true]);

        try {
            $this->editor()->apply($edit, $this->user);
            $this->fail('The edit was applied while writes were paused.');
        } catch (EditRefused $exception) {
            $this->assertStringContainsString('Nothing was sent', $exception->getMessage());
        }

        $this->assertSame(CampaignEntityEdit::Proposed, $edit->refresh()->state);
        $this->assertSame([], $this->writes);
    }

    public function test_the_change_cooldown_applies_to_the_manager_too(): void
    {
        config(['platforms.guardrails.change_cooldown_seconds' => 600]);
        $campaign = $this->read();
        CampaignChange::create(['campaign_id' => $campaign->id, 'actor' => 'chat', 'changes' => [], 'state' => 'applied', 'applied_at' => now()]);
        $edit = $this->editor()->propose($campaign, $this->entity($campaign, '2001'), $this->user, ['name' => 'Renamed']);

        $this->expectException(EditRefused::class);

        $this->editor()->apply($edit, $this->user);
    }

    public function test_only_the_proposer_can_apply_their_change(): void
    {
        $campaign = $this->read();
        $edit = $this->editor()->propose($campaign, $this->entity($campaign, '2001'), $this->user, ['name' => 'Renamed']);

        $this->expectException(EditRefused::class);

        $this->editor()->apply($edit, User::factory()->create());
    }

    public function test_editing_is_off_unless_the_platform_is_switched_on(): void
    {
        config(['campaign-manager.edit_platforms' => []]);
        $campaign = $this->read();

        $this->expectException(EditRefused::class);
        $this->expectExceptionMessage('not switched on');

        $this->editor()->propose($campaign, $this->entity($campaign, '2001'), $this->user, ['name' => 'Renamed']);
    }

    public function test_only_names_can_be_changed(): void
    {
        $campaign = $this->read();

        $this->expectException(EditRefused::class);
        $this->expectExceptionMessage('daily_budget cannot be changed here');

        $this->editor()->propose($campaign, $this->entity($campaign, '2001'), $this->user, ['name' => 'Renamed', 'daily_budget' => 40]);
    }

    public function test_an_unchanged_name_is_not_proposed(): void
    {
        $campaign = $this->read();

        $this->expectException(EditRefused::class);

        $this->editor()->propose($campaign, $this->entity($campaign, '2001'), $this->user, ['name' => 'US mobile ']);
    }

    public function test_a_blank_or_overlong_name_is_rejected(): void
    {
        $campaign = $this->read();
        $adSet = $this->entity($campaign, '2001');

        foreach (['', str_repeat('a', 251), "line\nbreak"] as $name) {
            try {
                $this->editor()->propose($campaign, $adSet, $this->user, ['name' => $name]);
                $this->fail('Accepted '.json_encode($name));
            } catch (ValidationException $exception) {
                $this->assertArrayHasKey('name', $exception->errors());
            }
        }

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

    // ------------------------------------------------------- Google, LinkedIn

    public function test_a_google_campaign_is_renamed_with_a_name_only_update(): void
    {
        config(['services.google_ads.refresh_token' => 'token', 'services.google_ads.customer_id' => '3460855874']);
        $profile = ['id' => '987', 'name' => 'Search - brand', 'status' => 'ENABLED'];

        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readManagerCriteria')->andReturn([]);
        $google->shouldReceive('readCampaignProfile')->andReturnUsing(function () use (&$profile): array {
            return $profile;
        });
        $google->shouldReceive('readCampaignStructure')->andReturn(['ad_groups' => [], 'ads' => [], 'asset_groups' => []]);
        $google->shouldReceive('updateLiveCampaign')->once()
            ->withArgs(fn ($connection, string $id, array $fields): bool => $id === '987' && $fields === ['name' => 'Search - brand 2'])
            ->andReturnUsing(function () use (&$profile): void {
                $profile['name'] = 'Search - brand 2';
            });
        $this->app->instance(GoogleAdsService::class, $google);

        $campaign = $this->read($this->campaign(['platform' => 'google', 'ad_account_id' => '3460855874', 'external_campaign_id' => '987']));
        $edit = $this->editor()->propose($campaign, $this->entity($campaign, '987'), $this->user, ['name' => 'Search - brand 2']);

        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user)->state);
    }

    public function test_a_linkedin_creative_name_is_limited_to_200_bytes_and_renamed(): void
    {
        $creative = ['id' => 'urn:li:sponsoredCreative:77', 'name' => 'Old', 'campaign' => 'urn:li:sponsoredCampaign:555', 'intendedStatus' => 'ACTIVE'];

        $linkedin = Mockery::mock(LinkedIn::class);
        $linkedin->shouldReceive('campaignConversions')->andReturn([]);
        $linkedin->shouldReceive('on')->andReturnSelf();
        $linkedin->shouldReceive('campaign')->andReturn(['id' => 555, 'name' => 'Lead gen', 'status' => 'ACTIVE', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:44']);
        $linkedin->shouldReceive('campaignGroup')->andReturn(['id' => 44, 'name' => 'Q4', 'status' => 'ACTIVE']);
        $linkedin->shouldReceive('creatives')->andReturnUsing(function () use (&$creative): array {
            return ['elements' => [$creative], 'next_page_token' => null];
        });
        $linkedin->shouldReceive('updateEntity')->once()
            ->with('urn:li:sponsoredAccount:999', 'creative', '77', ['name' => 'New'])
            ->andReturnUsing(function () use (&$creative): void {
                $creative['name'] = 'New';
            });
        $this->app->instance(LinkedIn::class, $linkedin);

        $campaign = $this->read($this->campaign(['platform' => 'linkedin', 'ad_account_id' => 'urn:li:sponsoredAccount:999', 'external_campaign_id' => '555']));
        $entity = $this->entity($campaign, '77');

        try {
            $this->editor()->propose($campaign, $entity, $this->user, ['name' => str_repeat('é', 101)]);
            $this->fail('A 202-byte LinkedIn name was accepted.');
        } catch (ValidationException) {
        }

        $edit = $this->editor()->propose($campaign, $entity, $this->user, ['name' => 'New']);

        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user)->state);
    }

    // ---------------------------------------------------------------- wizard

    public function test_the_wizard_reviews_then_applies_a_rename(): void
    {
        $campaign = $this->read();
        $adSet = $this->entity($campaign, '2001');

        $this->actingAs($this->user)->get(route('campaign-manager.show', $campaign))
            ->assertOk()
            ->assertSee(route('campaign-manager.edit', [$campaign->id, $adSet->id]), false);

        $wizard = Livewire::actingAs($this->user)
            ->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $adSet])
            ->assertSet('values.name', 'US mobile')
            ->set('values.name', 'US mobile - spring')
            ->call('review')
            ->assertHasNoErrors()
            ->assertSee('Confirm and apply')
            ->assertSee('US mobile - spring');

        $this->assertSame([], $this->writes);

        $wizard->call('confirm')->assertSee('Done.');

        $this->assertSame(CampaignEntityEdit::Applied, CampaignEntityEdit::sole()->state);
        $this->actingAs($this->user)->get(route('campaign-manager.show', $campaign))
            ->assertSee('Applied and confirmed')
            ->assertSee('Edited here');
    }

    public function test_the_wizard_shows_validation_errors_against_the_field(): void
    {
        $campaign = $this->read();

        Livewire::actingAs($this->user)
            ->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $this->entity($campaign, '2001')])
            ->set('values.name', '')
            ->call('review')
            ->assertHasErrors(['values.name']);

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

    public function test_the_wizard_cannot_be_pointed_at_another_object(): void
    {
        $campaign = $this->read();

        $this->expectException(CannotUpdateLockedPropertyException::class);

        Livewire::actingAs($this->user)
            ->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $this->entity($campaign, '2001')])
            ->set('entityId', $this->entity($campaign, '3001')->id);
    }

    public function test_another_users_object_is_not_found(): void
    {
        $campaign = $this->read();
        $adSet = $this->entity($campaign, '2001');

        $this->actingAs(User::factory()->create())
            ->get(route('campaign-manager.edit', [$campaign->id, $adSet->id]))
            ->assertNotFound();
    }

    public function test_an_object_from_another_campaign_is_not_found(): void
    {
        $campaign = $this->read();
        $other = $this->campaign(['name' => 'Other']);
        $adSet = $this->entity($campaign, '2001');

        $this->actingAs($this->user)
            ->get(route('campaign-manager.edit', [$other->id, $adSet->id]))
            ->assertNotFound();
    }

    public function test_no_edit_link_is_shown_while_editing_is_off(): void
    {
        config(['campaign-manager.edit_platforms' => []]);
        $campaign = $this->read();

        $this->actingAs($this->user)->get(route('campaign-manager.show', $campaign))
            ->assertOk()
            ->assertDontSee('/entities/', false);
    }
}
