<?php

namespace Tests\Feature;

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

/**
 * Duplicating an ad set keeps it in the same campaign.
 *
 * The copy has to carry the city, the gender, the interests and the ads. A
 * second ad set that only kept the country was a wider audience than the one
 * the user asked to duplicate.
 */
class DuplicateAdSetTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

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

        $this->seedVerifiedCountries();
        $this->actingAs(User::factory()->create());

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-duplicate-ad-set');
        $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_the_copy_keeps_the_city_gender_interests_and_ads(): void
    {
        $campaign = $this->campaignWithNewYork();
        $this->fakeMeta();

        $result = $this->duplicate();

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? json_encode($result));

        $copy = $campaign->adSets()->where('position', 2)->first();

        $this->assertNotNull($copy);
        $this->assertSame('adset-copy', $copy->external_adset_id);
        $this->assertSame('120222', $copy->audience['duplicate_of']);
        $this->assertSame([1], $copy->audience['genders']);
        $this->assertSame('6003139266461', $copy->audience['meta_interests'][0]['id']);
        $ad = $copy->ads()->first();
        $this->assertSame('Block pop-ups', $ad->headline);
        $this->assertSame('ad-copy', $ad->external_ad_id);
        $this->assertSame('120222', $campaign->primaryAdSet->fresh()->external_adset_id);

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

            return str_ends_with($path, '/120222/copies')
                && $request['campaign_id'] === '120111'
                && $request['deep_copy'] === 'true'
                && $request['status_option'] === 'ACTIVE'
                && str_contains((string) $request['rename_options'], ' - copy')
                && str_contains((string) $request['rename_options'], 'DEEP_RENAME');
        });
    }

    public function test_asking_in_chat_copies_the_ad_set_instead_of_narrating(): void
    {
        $this->campaignWithNewYork();
        $this->fakeMeta();

        $method = new ReflectionMethod(ChatController::class, 'duplicateAdSetFromMessage');
        $reply = $method->invoke(app(ChatController::class), 'Create the duplicate adset in this campaign along with the creative');

        $this->assertStringContainsString('active', strtolower((string) $reply));
        Http::assertSent(fn ($request): bool => str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/120222/copies'));
    }

    public function test_several_ad_sets_are_asked_about_before_anything_is_created(): void
    {
        $campaign = $this->campaignWithNewYork();
        $campaign->adSets()->create([
            'name' => 'Second', 'position' => 2, 'external_adset_id' => '120333', 'status' => 'published',
            'locations' => ['countries' => ['US']],
        ]);
        Http::fake();

        $result = $this->duplicate();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Which ad set', $result['ask']);
        $this->assertCount(2, $result['ad_sets']);
        $this->assertSame(2, $campaign->adSets()->count());
        Http::assertNothingSent();
    }

    public function test_a_pixel_the_account_cannot_use_asks_for_one_that_it_can(): void
    {
        $campaign = $this->campaignWithNewYork();
        $campaign->update(['pixel_id' => '1758028222031674']);
        Http::fake(function ($request) {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            if (str_contains($path, '/copies')) {
                return Http::response(['error' => [
                    'message' => 'Account 1418821929380936 does not have access to pixel 1758028222031674',
                    'type' => 'OAuthException',
                    'code' => 200,
                    'error_subcode' => 1815045,
                    'error_user_msg' => 'This campaign can\'t run because it\'s associated with a pixel ID that your ad account does not have access to.',
                ]], 400);
            }

            if (str_contains($path, '/adspixels')) {
                return Http::response(['data' => [
                    ['id' => '111222', 'name' => 'Account Pixel'],
                    ['id' => '333444', 'name' => 'Other Pixel'],
                ]]);
            }

            return Http::response(['id' => 'act_111', 'name' => 'Account']);
        });

        $result = $this->duplicate();

        $this->assertFalse($result['ok']);
        $this->assertTrue($result['needs_pixel']);
        $this->assertStringContainsString('Choose a pixel', $result['ask']);
        $this->assertSame(1, $campaign->adSets()->count());
        $this->assertSame('1758028222031674', $campaign->fresh()->pixel_id);

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

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

            if (str_contains($path, '/adspixels')) {
                return Http::response(['data' => [['id' => '111222', 'name' => 'Account Pixel']]]);
            }

            if ($method === 'GET' && str_ends_with($path, '/120222/ads')) {
                return Http::response(['data' => [[
                    'id' => 'ad-1',
                    'name' => 'Block pop-ups',
                    'creative' => ['id' => 'creative-1'],
                ]]]);
            }

            if ($method === 'GET' && str_ends_with($path, '/120222')) {
                return Http::response([
                    'id' => '120222',
                    'name' => 'New York men',
                    'billing_event' => 'IMPRESSIONS',
                    'optimization_goal' => 'LINK_CLICKS',
                    'daily_budget' => '2000',
                    'targeting' => [
                        'geo_locations' => ['cities' => [['key' => '2427173', 'name' => 'New York']]],
                        'genders' => [1],
                        'interests' => [['id' => '6003139266461', 'name' => 'Privacy policy']],
                        'age_min' => 18,
                        'age_max' => 55,
                    ],
                    'promoted_object' => ['pixel_id' => '1758028222031674', 'custom_event_type' => 'PURCHASE'],
                ]);
            }

            if ($method === 'POST' && str_ends_with($path, '/adsets')) {
                return Http::response(['id' => 'adset-copy']);
            }

            if ($method === 'POST' && str_contains($path, '/ad-1/copies')) {
                return Http::response(['copied_ad_id' => 'ad-copy']);
            }

            return Http::response(['id' => 'act_111', 'name' => 'Account']);
        });

        $result = $this->duplicate(['ad_set_id' => '120222', 'pixel_id' => '111222']);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? json_encode($result));
        $copy = $campaign->adSets()->where('position', 2)->first();
        $this->assertSame('adset-copy', $copy->external_adset_id);
        $this->assertSame('111222', $copy->audience['pixel_id']);
        $this->assertSame('ad-copy', $copy->ads()->first()->external_ad_id);
        $this->assertSame('120222', $campaign->primaryAdSet->fresh()->external_adset_id);

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

            return $request->method() === 'POST'
                && str_ends_with($path, '/adsets')
                && str_contains((string) $request['targeting'], '2427173')
                && str_contains((string) $request['targeting'], '6003139266461')
                && str_contains((string) $request['promoted_object'], '111222')
                && ! str_contains((string) $request['promoted_object'], '1758028222031674')
                && $request['status'] === 'PAUSED';
        });
        Http::assertNotSent(fn ($request): bool => str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/120222/copies'));
    }

    public function test_a_stale_place_mapping_still_copies_on_meta(): void
    {
        $campaign = $this->campaignWithNewYork();
        PlatformLocation::query()->update(['verified_at' => now()->subDays(31)]);
        $this->fakeMeta();

        $result = $this->duplicate();

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? json_encode($result));
        $this->assertSame(2, $campaign->adSets()->count());
        Http::assertSent(fn ($request): bool => str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/120222/copies'));
    }

    public function test_an_ad_set_can_be_copied_into_another_campaign_on_the_same_account(): void
    {
        $source = $this->campaignWithNewYork();
        $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',
        ]);
        app(Workspace::class)->focusOn($source);
        $this->fakeMeta();

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

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? json_encode($result));
        $this->assertSame('120999', $result['destination_campaign_id']);
        $copy = $destination->adSets()->where('external_adset_id', 'adset-copy')->first();
        $this->assertNotNull($copy);
        $this->assertSame('Block pop-ups', $copy->ads()->first()->headline);
        $this->assertSame('120222', $source->primaryAdSet->fresh()->external_adset_id);
        $this->assertSame(1, $source->adSets()->count());

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

            return str_ends_with($path, '/120222/copies') && $request['campaign_id'] === '120999';
        });
    }

    public function test_a_different_ad_account_is_refused(): void
    {
        $source = $this->campaignWithNewYork();
        Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Other account',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'currency' => 'USD',
            'budget' => 20,
            'budget_mode' => 'daily',
            'ad_account_id' => 'act_222',
            'external_campaign_id' => '120888',
        ]);
        app(Workspace::class)->focusOn($source);
        Http::fake();

        $result = $this->duplicate([
            'ad_set_id' => '120222',
            'destination_campaign_id' => '120888',
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('different ad accounts', $result['error']);
        Http::assertNothingSent();
    }

    public function test_asking_in_chat_copies_into_the_named_campaign_even_when_it_is_not_stored(): void
    {
        $this->campaignWithNewYork();
        $this->fakeMeta();

        $reply = (new ReflectionMethod(ChatController::class, 'duplicateAdSetFromMessage'))->invoke(
            app(ChatController::class),
            'can you duplicate this adset 120252613312530100 from this campaign id 120252613312230100 to this campaign 120248697937850100',
        );

        $this->assertStringContainsString('120248697937850100', (string) $reply);
        $this->assertStringContainsString('active', strtolower((string) $reply));
        Http::assertSent(function ($request): bool {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            return str_ends_with($path, '/120252613312530100/copies')
                && $request['campaign_id'] === '120248697937850100';
        });
    }

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

        $this->assertNotNull($tool);

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

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

            return match (true) {
                str_contains($path, '/copies') => Http::response([
                    'copied_adset_id' => 'adset-copy',
                    'ad_object_ids' => [
                        ['ad_object_type' => 'ad_set', 'source_id' => '120222', 'copied_id' => 'adset-copy'],
                        ['ad_object_type' => 'ad', 'source_id' => 'ad-1', 'copied_id' => 'ad-copy'],
                    ],
                ]),
                default => Http::response(['success' => true]),
            };
        });
    }

    private function campaignWithNewYork(): 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',
            'budget_level' => 'adset',
            'ad_account_id' => 'act_111',
            'page_id' => 'page-1',
            'landing_url' => 'https://example.com/offer',
            'locations' => ['countries' => ['US']],
            'placements' => ['facebook'],
            'audience' => [
                'age_min' => 18,
                'age_max' => 55,
                'genders' => [1],
                'meta_interests' => [['id' => '6003139266461', 'name' => 'Privacy policy']],
            ],
            'external_campaign_id' => '120111',
            'external_ids' => ['campaign_id' => '120111', 'adset_id' => '120222'],
        ]);

        $campaign->primaryAdSet->update([
            'external_adset_id' => '120222',
            'status' => 'published',
        ]);

        // A city has no ISO country code of its own, and the factory's default is
        // a country, so without this the row takes a real country's code: a city
        // named "France" holding iso_code FR. locations.iso_code is globally
        // unique, so it then collided with the seeded countries at random and
        // this test failed whenever the faker happened to pick a seeded one.
        $location = Location::factory()->create([
            'type' => 'city',
            'country_code' => 'US',
            'iso_code' => null,
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->id,
            'platform' => 'meta',
            'external_id' => '2427173',
            'status' => 'verified',
            'verified_at' => now(),
        ]);
        $set = TargetingSet::factory()->forCampaign($campaign)->create();
        $set->locations()->create([
            'operation' => 'include', 'kind' => 'country', 'country_code' => 'US', 'display_label' => 'United States',
        ]);
        $set->locations()->create([
            'location_id' => $location->id,
            'platform_location_id' => $mapping->id,
            'kind' => 'city',
            'operation' => 'include',
            'country_code' => 'US',
            'display_label' => 'New York',
        ]);

        $asset = Asset::create([
            'owner_type' => (new User)->getMorphClass(),
            'owner_id' => $campaign->user_id,
            'kind' => 'image', 'source' => 'generated', 'disk' => 'public',
            'path' => 'creatives/x.png', 'original_name' => 'x.png',
            'mime' => 'image/png', 'bytes' => 10, 'checksum' => 'sum',
        ]);
        AssetPlatformRef::create([
            'asset_id' => $asset->id, 'platform' => 'meta',
            'ad_account_id' => 'act_111', 'external_hash' => 'HASH123',
        ]);
        $campaign->ads()->create([
            'ad_set_id' => $campaign->primaryAdSet->id,
            'headline' => 'Block pop-ups',
            'primary_text' => 'A cleaner browser.',
            'cta' => 'LEARN_MORE',
            'asset_id' => $asset->id,
            'external_ad_id' => 'ad-1',
            'external_creative_id' => 'creative-1',
            'status' => 'published',
        ]);

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

        return $campaign->fresh();
    }
}
