<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Http\Controllers\ChatController;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use ReflectionMethod;
use Tests\TestCase;

/**
 * An ad is copied into an ad set the user names, or one they pick.
 */
class DuplicateAdTest extends TestCase
{
    use RefreshDatabase;

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

        $this->actingAs(User::factory()->create());
        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-duplicate-ad');
        $workspace->ownedBy(auth()->user());

        config([
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['act_111'],
            'platforms.guardrails.max_daily_budget' => 500,
        ]);
    }

    public function test_a_missing_ad_set_is_asked_for_before_anything_is_copied(): void
    {
        $campaign = $this->campaign();
        Http::fake();

        $result = $this->duplicate(['ad_id' => '120210']);

        $this->assertFalse($result['ok']);
        $this->assertTrue($result['needs_ad_set']);
        $this->assertStringContainsString('Which ad set', $result['ask']);
        $this->assertSame(1, $campaign->ads()->count());
        Http::assertNothingSent();

        $choice = collect(app(Choices::class)->all())->firstWhere('field', 'duplicate_ad_adset');
        $this->assertSame(['120210|120222', '120210|120333'], array_column($choice['options'], 'value'));
    }

    public function test_the_named_ad_is_copied_into_the_named_ad_set_and_paused(): void
    {
        $campaign = $this->campaign();
        Http::fake(function ($request) {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            if (str_contains($path, '/120210/copies')) {
                return Http::response(['copied_ad_id' => '120999']);
            }

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

        $result = $this->duplicate(['ad_id' => '120210', 'ad_set_id' => '120333']);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? json_encode($result));
        $this->assertSame('ACTIVE', $result['status']);
        $copy = $campaign->ads()->where('external_ad_id', '120999')->first();
        $this->assertNotNull($copy);
        $this->assertSame('Block pop-ups', $copy->headline);
        $this->assertSame('published', $copy->status);
        $this->assertSame(
            $campaign->adSets()->where('external_adset_id', '120333')->value('id'),
            $copy->ad_set_id,
        );

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

            return str_ends_with($path, '/120210/copies')
                && $request['adset_id'] === '120333'
                && $request['status_option'] === 'ACTIVE';
        });
    }

    public function test_a_named_ad_account_copies_the_live_ad_when_this_campaign_has_none(): void
    {
        $campaign = $this->campaign();
        $campaign->ads()->delete();
        Http::fake(fn () => Http::response([
            'copied_ad_id' => '120999',
            'status_option' => 'ACTIVE',
        ]));

        $method = new ReflectionMethod(ChatController::class, 'duplicateAdFromMessage');
        $reply = $method->invoke(
            app(ChatController::class),
            'can you duplicate this ad id 120248690751510100 and create a new one in the same ad set 120248690751520100 and campaign id 120248690751530100 for ad account 111',
            [],
        );

        $this->assertStringContainsString('Duplicated The ad into ad set 120248690751520100', (string) $reply);
        $this->assertStringNotContainsString('no published ad', (string) $reply);
        Http::assertSent(function ($request): bool {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            return str_ends_with($path, '/120248690751510100/copies')
                && $request['adset_id'] === '120248690751520100';
        });
    }

    public function test_given_copy_is_written_onto_the_duplicated_ad(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['external_campaign_id' => '120248690751530100']);
        $campaign->primaryAdSet->update(['external_adset_id' => '120248690751520100']);
        $campaign->ads()->delete();

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

            if (str_ends_with($path, '/copies')) {
                return Http::response(['copied_ad_id' => '120252845123610100']);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/120252845123610100')) {
                return Http::response([
                    'id' => '120252845123610100',
                    'campaign_id' => '120248690751530100',
                    'account_id' => '111',
                    'creative' => [
                        'object_story_spec' => [
                            'page_id' => 'page-1',
                            'video_data' => [
                                'video_id' => 'vid-1',
                                'image_url' => 'https://scontent.example/thumb.jpg',
                                'image_hash' => 'HASH1',
                                'message' => 'Old body',
                                'title' => 'Old headline',
                                'link_description' => 'Old description',
                                'call_to_action' => [
                                    'type' => 'SIGN_UP',
                                    'value' => ['link' => 'https://old.example'],
                                ],
                            ],
                        ],
                    ],
                ]);
            }

            if (str_contains($path, '/adcreatives')) {
                return Http::response(['id' => 'creative-new']);
            }

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

        $method = new ReflectionMethod(ChatController::class, 'duplicateAdFromMessage');
        $reply = $method->invoke(
            app(ChatController::class),
            implode("\n", [
                'Duplicate ad 120248690751510100 into ad set 120248690751520100 in campaign 120248690751530100 for ad account act_111.',
                'Primary text: Researching stocks can be overwhelming.',
                'Headline: Compare the reports.',
                'Description: A short summary of what matters.',
                'URL: abc.com',
                'Call to action: SHOP_NOW',
            ]),
            [],
        );

        $this->assertStringContainsString('Duplicated Compare the reports. into ad set 120248690751520100', (string) $reply);
        $this->assertStringContainsString('The new copy is on that ad.', (string) $reply);

        $copy = $campaign->ads()->where('external_ad_id', '120252845123610100')->first();
        $this->assertNotNull($copy);
        $this->assertSame('Compare the reports.', $copy->headline);
        $this->assertSame('Researching stocks can be overwhelming.', $copy->primary_text);
        $this->assertSame('A short summary of what matters.', $copy->description);
        $this->assertSame('SHOP_NOW', $copy->cta);

        Http::assertSent(function ($request): bool {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);
            $story = json_decode((string) ($request['object_story_spec'] ?? ''), true);
            $video = is_array($story) ? ($story['video_data'] ?? []) : [];

            return str_contains($path, '/adcreatives')
                && ($video['message'] ?? null) === 'Researching stocks can be overwhelming.'
                && ($video['title'] ?? null) === 'Compare the reports.'
                && ($video['link_description'] ?? null) === 'A short summary of what matters.'
                && ($video['call_to_action']['type'] ?? null) === 'SHOP_NOW'
                && ($video['call_to_action']['value']['link'] ?? null) === 'https://abc.com'
                && ($video['image_hash'] ?? null) === 'HASH1'
                && ! array_key_exists('image_url', $video);
        });
    }

    public function test_a_button_can_be_typed_as_words(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['external_campaign_id' => '120248690751530100']);
        $campaign->primaryAdSet->update(['external_adset_id' => '120248690751520100']);
        $campaign->ads()->delete();

        $labels = [
            'Learn More' => 'LEARN_MORE',
            'shop now' => 'SHOP_NOW',
            'sign-up' => 'SIGN_UP',
            'Get Offer' => 'GET_OFFER',
            'Subscribe' => 'SUBSCRIBE',
            'contact us' => 'CONTACT_US',
            'book-travel' => 'BOOK_TRAVEL',
        ];

        foreach ($labels as $typed => $code) {
            Http::fake(function ($request) {
                $path = (string) parse_url($request->url(), PHP_URL_PATH);

                if (str_ends_with($path, '/copies')) {
                    return Http::response(['copied_ad_id' => '120252845123610100']);
                }

                if ($request->method() === 'GET' && str_ends_with($path, '/120252845123610100')) {
                    return Http::response([
                        'id' => '120252845123610100',
                        'campaign_id' => '120248690751530100',
                        'account_id' => '111',
                        'creative' => [
                            'object_story_spec' => [
                                'page_id' => 'page-1',
                                'link_data' => [
                                    'link' => 'https://old.example',
                                    'message' => 'Old',
                                    'call_to_action' => ['type' => 'LEARN_MORE', 'value' => ['link' => 'https://old.example']],
                                ],
                            ],
                        ],
                    ]);
                }

                return Http::response($request->method() === 'POST' && str_contains($path, '/adcreatives')
                    ? ['id' => 'creative-new']
                    : ['success' => true]);
            });

            $method = new ReflectionMethod(ChatController::class, 'duplicateAdFromMessage');
            $reply = $method->invoke(
                app(ChatController::class),
                "Duplicate ad 120248690751510100 into ad set 120248690751520100 in campaign 120248690751530100 for ad account act_111.\nCall to action: {$typed}",
                [],
            );

            $this->assertStringContainsString('The new copy is on that ad.', (string) $reply, $typed);
            Http::assertSent(function ($request) use ($code): bool {
                $story = json_decode((string) ($request['object_story_spec'] ?? ''), true);

                return ($story['link_data']['call_to_action']['type'] ?? null) === $code;
            });
        }
    }

    public function test_an_unknown_call_to_action_is_refused_before_the_copy(): void
    {
        $this->campaign();
        Http::fake();

        $method = new ReflectionMethod(ChatController::class, 'duplicateAdFromMessage');
        $reply = $method->invoke(
            app(ChatController::class),
            "Duplicate ad 120210 into ad set 120333 in campaign 120111 for ad account act_111.\nCall to action: BUY_NOW",
            [],
        );

        $this->assertStringContainsString('SHOP_NOW', (string) $reply);
        $this->assertStringContainsString('BOOK_TRAVEL', (string) $reply);
        Http::assertNothingSent();
    }

    public function test_asking_to_duplicate_an_ad_offers_the_ad_sets(): void
    {
        $this->campaign();
        Http::fake();

        $method = new ReflectionMethod(ChatController::class, 'duplicateAdFromMessage');
        $reply = $method->invoke(app(ChatController::class), 'duplicate this ad', []);

        $this->assertStringContainsString('Which ad set', (string) $reply);
        Http::assertNothingSent();
    }

    public function test_an_ad_can_be_copied_into_an_ad_set_on_another_campaign(): void
    {
        $source = $this->campaign();
        $destination = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Other',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'currency' => 'USD',
            'budget' => 20,
            'budget_mode' => 'daily',
            'ad_account_id' => 'act_111',
            'external_campaign_id' => '120999',
        ]);
        $destination->primaryAdSet->update([
            'external_adset_id' => '120444',
            'status' => 'published',
        ]);
        app(Workspace::class)->focusOn($source);
        Http::fake(fn () => Http::response([
            'copied_ad_id' => 'ad-copy',
            'status_option' => 'ACTIVE',
        ]));

        $result = $this->duplicate([
            'ad_id' => '120210',
            'destination_campaign_id' => '120999',
        ]);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? json_encode($result));
        $this->assertSame('120444', $result['ad_set_id']);
        $this->assertSame('ad-copy', $destination->ads()->first()->external_ad_id);
        $this->assertSame('Block pop-ups', $destination->ads()->first()->headline);
        Http::assertSent(function ($request): bool {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            return str_ends_with($path, '/120210/copies') && $request['adset_id'] === '120444';
        });
    }

    /** @return array<string, mixed> */
    private function duplicate(array $arguments = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($tool) => $tool->name() === 'campaign__duplicate_ad');

        $this->assertNotNull($tool);

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    private function campaign(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Block Ads',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'currency' => 'USD',
            'budget' => 20,
            'budget_mode' => 'daily',
            'ad_account_id' => 'act_111',
            'page_id' => 'page-1',
            'landing_url' => 'https://example.com/offer',
            'external_campaign_id' => '120111',
        ]);

        $campaign->primaryAdSet->update([
            'name' => 'First',
            'external_adset_id' => '120222',
            'status' => 'published',
        ]);
        $campaign->adSets()->create([
            'name' => 'Second',
            'position' => 2,
            'external_adset_id' => '120333',
            'status' => 'published',
        ]);
        $campaign->ads()->create([
            'ad_set_id' => $campaign->primaryAdSet->id,
            'headline' => 'Block pop-ups',
            'primary_text' => 'A cleaner browser.',
            'cta' => 'LEARN_MORE',
            'external_ad_id' => '120210',
            'status' => 'published',
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);

        return $campaign->fresh();
    }
}
