<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\Tools\Campaign\EditEntity;
use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\CampaignChange;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

class PublishedAdCreativeEditTest extends TestCase
{
    use RefreshDatabase;

    private Campaign $campaign;

    private array $ad;

    private array $created = [];

    private bool $applyUpdate = true;

    private bool $failReadback = false;

    private bool $changeWhilePreparing = false;

    private bool $ignoreNewCta = false;

    protected function setUp(): void
    {
        parent::setUp();
        config([
            'platforms.meta.token' => 'test-token', 'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:act_111'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 20,
        ]);
        $user = User::factory()->create();
        $this->actingAs($user);
        $workspace = app(Workspace::class);
        $workspace->bindTo('creative-edit');
        $workspace->ownedBy($user);
        $this->campaign = Campaign::create([
            'user_id' => $user->id, 'name' => 'Imported campaign', 'platform' => 'meta',
            'status' => 'published', 'ad_account_id' => 'act_111', 'external_campaign_id' => 'campaign-1',
        ]);
        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign);
        $this->ad = [
            'id' => 'ad-1', 'name' => 'Live ad', 'status' => 'ACTIVE', 'effective_status' => 'ACTIVE',
            'campaign_id' => 'campaign-1', 'account_id' => '111',
            'creative' => [
                'id' => 'old-creative',
                'object_story_spec' => ['page_id' => 'page-1', 'instagram_user_id' => 'ig-1'],
                'url_tags' => 'utm_content={{ad.id}}',
                'degrees_of_freedom_spec' => ['creative_features_spec' => ['text_optimizations' => ['enroll_status' => 'OPT_OUT']]],
                'asset_feed_spec' => [
                    'ad_formats' => ['SINGLE_IMAGE'],
                    'images' => [['hash' => 'image-1', 'adlabels' => [['name' => 'feed-image']]], ['hash' => 'image-2']],
                    'bodies' => [['text' => 'Old body', 'adlabels' => [['name' => 'feed-body']]], ['text' => 'Other body']],
                    'titles' => [['text' => 'Old headline', 'adlabels' => [['name' => 'feed-title']]]],
                    'descriptions' => [['text' => 'Old description']],
                    'link_urls' => [
                        ['website_url' => 'https://example.com/a?ad={{ad.id}}', 'adlabels' => [['name' => 'feed-link']]],
                        ['website_url' => 'https://example.com/b'],
                    ],
                    'call_to_action_types' => ['LEARN_MORE'],
                    'asset_customization_rules' => [[
                        'customization_spec' => ['publisher_platforms' => ['facebook']],
                        'image_label' => ['name' => 'feed-image'], 'body_label' => ['name' => 'feed-body'],
                        'title_label' => ['name' => 'feed-title'], 'link_url_label' => ['name' => 'feed-link'],
                    ]],
                ],
            ],
        ];
        Http::fake(function ($request) {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);
            if ($request->method() === 'GET' && str_ends_with($path, '/ad-1')) {
                if ($this->failReadback && $this->ad['creative']['id'] === 'new-creative') {
                    return Http::response(['error' => ['message' => 'Readback unavailable']], 400);
                }

                return Http::response($this->ad);
            }
            if ($request->method() === 'POST' && str_ends_with($path, '/adcreatives')) {
                $this->created = ['id' => 'new-creative'];
                foreach (['object_story_spec', 'asset_feed_spec', 'degrees_of_freedom_spec'] as $field) {
                    if (isset($request[$field])) {
                        $this->created[$field] = json_decode($request[$field], true, flags: JSON_THROW_ON_ERROR);
                    }
                }
                $this->created['url_tags'] = $request['url_tags'] ?? null;
                if ($this->changeWhilePreparing) {
                    $this->ad['creative']['asset_feed_spec']['bodies'][0]['text'] = 'Changed outside Arb';
                }

                return Http::response(['id' => 'new-creative']);
            }
            if ($request->method() === 'POST' && str_ends_with($path, '/ad-1')) {
                if ($this->applyUpdate) {
                    $this->ad['creative'] = $this->created;
                    $this->ad['name'] = $request['name'] ?? $this->ad['name'];
                    if ($this->ignoreNewCta) {
                        $this->ad['creative']['asset_feed_spec']['call_to_action_types'] = ['LEARN_MORE'];
                    }
                }

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

            $this->fail('Unexpected platform request: '.$request->method().' '.$path);
        });
    }

    private function tool(): NamespacedTool
    {
        return new NamespacedTool('campaign', app(EditEntity::class));
    }

    private function request(array $changes = ['cta' => 'GET_QUOTE'], ?string $callId = null): Request
    {
        return new Request(['entity_type' => 'ad', 'id' => 'ad-1', ...$changes], $callId);
    }

    private function edit(Request $request): array
    {
        return json_decode((string) $this->tool()->handle($request), true, flags: JSON_THROW_ON_ERROR);
    }

    public function test_an_approved_dynamic_creative_edit_preserves_media_links_labels_and_identity(): void
    {
        $before = $this->ad['creative'];
        $request = $this->request(['cta' => 'GET_QUOTE', 'primary_text' => 'New body',
            'headline' => 'New headline', 'description' => 'New description', 'name' => 'Renamed ad'], 'approved-edit');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $this->assertSame(['GET_QUOTE'], $this->created['asset_feed_spec']['call_to_action_types']);
        $this->assertSame(['New body', 'New body'], array_column($this->created['asset_feed_spec']['bodies'], 'text'));
        $this->assertSame('New headline', $this->created['asset_feed_spec']['titles'][0]['text']);
        $this->assertSame('New description', $this->created['asset_feed_spec']['descriptions'][0]['text']);
        foreach (['images', 'link_urls', 'asset_customization_rules', 'ad_formats'] as $field) {
            $this->assertSame($before['asset_feed_spec'][$field], $this->created['asset_feed_spec'][$field]);
        }
        $this->assertSame($before['asset_feed_spec']['bodies'][0]['adlabels'], $this->created['asset_feed_spec']['bodies'][0]['adlabels']);
        $this->assertSame($before['object_story_spec'], $this->created['object_story_spec']);
        $this->assertSame($before['url_tags'], $this->created['url_tags']);
        $this->assertSame($before['degrees_of_freedom_spec'], $this->created['degrees_of_freedom_spec']);
        $this->assertSame('Renamed ad', $this->ad['name']);
        $this->assertSame(0, $this->campaign->ads()->count());
        $change = CampaignChange::sole();
        $this->assertSame('applied', $change->state);
        $this->assertSame('old-creative', $change->changes['previous_creative_id']);
        $this->assertSame('new-creative', $change->changes['replacement_creative_id']);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'POST'
            && str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/ads'));
    }

    public function test_a_video_story_keeps_its_video_and_destination_while_updating_the_cta(): void
    {
        unset($this->ad['creative']['asset_feed_spec']);
        $this->ad['creative']['object_story_spec']['video_data'] = [
            'video_id' => 'video-1', 'message' => 'Existing video body', 'title' => 'Existing headline',
            'call_to_action' => ['type' => 'LEARN_MORE', 'value' => ['link' => 'https://example.com/video']],
        ];
        $result = $this->edit($this->request());
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $video = $this->created['object_story_spec']['video_data'];
        $this->assertSame('video-1', $video['video_id']);
        $this->assertSame('Existing video body', $video['message']);
        $this->assertSame('https://example.com/video', $video['call_to_action']['value']['link']);
        $this->assertSame('GET_QUOTE', $video['call_to_action']['type']);
    }

    public function test_a_changed_live_creative_invalidates_the_approval_before_any_write(): void
    {
        $request = $this->request(callId: 'stale-edit');
        $this->tool()->shouldRequestApproval($request);
        $this->ad['creative']['asset_feed_spec']['bodies'][0]['text'] = 'Changed in Ads Manager';
        $result = $this->edit($request);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('changed since approval', $result['error']);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'POST');
    }

    public function test_changed_arguments_and_reused_approvals_cannot_mutate_the_ad(): void
    {
        $request = $this->request(callId: 'bound-edit');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($this->request(['headline' => 'Unapproved'], 'bound-edit'));
        $this->assertFalse($result['ok']);
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'POST');
    }

    public function test_an_expired_approval_and_a_missing_approval_are_refused(): void
    {
        $request = $this->request(callId: 'expired-edit');
        $this->tool()->shouldRequestApproval($request);
        $this->travel(61)->minutes();
        $this->assertFalse($this->edit($request)['ok']);
        $this->assertFalse($this->edit($this->request(callId: 'missing-edit'))['ok']);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'POST');
    }

    public function test_another_campaign_or_account_cannot_be_edited_through_the_focused_campaign(): void
    {
        $this->assertFalse($this->edit($this->request(['cta' => 'GET_QUOTE', 'campaign_id' => 'other-campaign']))['ok']);
        $this->ad['campaign_id'] = 'other-campaign';
        $this->assertFalse($this->edit($this->request())['ok']);
        $this->ad['campaign_id'] = 'campaign-1';
        $this->ad['account_id'] = '222';
        $this->assertFalse($this->edit($this->request())['ok']);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'POST');
    }

    public function test_an_existing_post_is_refused_instead_of_being_silently_rebuilt(): void
    {
        $this->ad['creative']['object_story_id'] = 'page-1_post-1';
        $result = $this->edit($this->request());
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('unsupported existing-post', $result['error']);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'POST');
    }

    public function test_a_successful_post_without_matching_readback_is_not_success(): void
    {
        $this->applyUpdate = false;
        $result = $this->edit($this->request());
        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
        $this->assertStringContainsString('Do not claim nothing changed', $result['note']);
        $this->assertSame('failed', CampaignChange::sole()->state);
    }

    public function test_a_matching_creative_id_is_not_enough_when_the_requested_button_does_not_match(): void
    {
        $this->ignoreNewCta = true;
        $result = $this->edit($this->request());
        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
        $this->assertSame('new-creative', $this->ad['creative']['id']);
        $this->assertStringContainsString('requested cta', $result['error']);
    }

    public function test_a_readback_failure_does_not_claim_the_running_ad_is_unchanged(): void
    {
        $local = $this->campaign->ads()->create([
            'external_ad_id' => 'ad-1', 'external_creative_id' => 'old-creative', 'cta' => 'LEARN_MORE',
            'headline' => 'Old headline', 'primary_text' => 'Old body',
        ]);
        $this->failReadback = true;
        $result = $this->edit($this->request());
        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
        $this->assertSame('new-creative', $this->ad['creative']['id']);
        $this->assertSame('old-creative', $local->fresh()->external_creative_id);
        $this->assertSame('LEARN_MORE', $local->fresh()->cta);
        $this->assertSame('new-creative', CampaignChange::sole()->changes['replacement_creative_id']);
    }

    public function test_a_live_change_during_creative_preparation_stops_the_attachment(): void
    {
        $this->changeWhilePreparing = true;
        $result = $this->edit($this->request());
        $this->assertFalse($result['ok']);
        $this->assertFalse($result['reconciliation_required']);
        $this->assertSame('old-creative', $this->ad['creative']['id']);
        $this->assertSame('new-creative', CampaignChange::sole()->changes['replacement_creative_id']);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'POST'
            && str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/ad-1'));
    }

    public function test_the_campaign_edit_lock_prevents_overlapping_creative_changes(): void
    {
        $lock = Cache::lock('campaign-manager:edit:'.$this->campaign->id, 300);
        $lock->get();
        try {
            $result = $this->edit($this->request());
            $this->assertFalse($result['ok']);
            $this->assertStringContainsString('Another edit', $result['error']);
            Http::assertNothingSent();
        } finally {
            $lock->release();
        }
    }

    public function test_creative_edits_respect_the_existing_change_cooldown(): void
    {
        config(['platforms.guardrails.change_cooldown_seconds' => 600]);
        CampaignChange::create(['campaign_id' => $this->campaign->id, 'actor' => 'previous-editor',
            'changes' => [], 'state' => 'applied', 'applied_at' => now()]);
        $result = $this->edit($this->request());
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('limited to one', $result['error']);
        Http::assertNothingSent();
    }
}
