<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Asset;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\TargetingSet;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Models\Conversation;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

class DuplicateCampaignTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->actingAs(User::factory()->create());
        app(Workspace::class)->bindTo('duplicate-campaign-conversation');
        app(Workspace::class)->ownedBy(auth()->user());
        Http::preventStrayRequests();
    }

    public function test_published_campaign_copies_budget_targeting_ad_sets_and_assets_as_draft(): void
    {
        $source = $this->sourceCampaign();
        $source->update([
            'budget' => 75, 'objective' => 'OUTCOME_SALES', 'ad_account_id' => 'act_123',
            'external_campaign_id' => 'remote-campaign', 'external_ids' => ['campaign' => 'remote-campaign'],
            'published_state' => ['budget' => 75], 'status' => 'published',
        ]);
        $source->primaryAdSet->update([
            'locations' => ['countries' => ['US']], 'audience' => ['age_min' => 25],
            'external_adset_id' => 'remote-set-1', 'status' => 'published',
        ]);
        $second = $source->adSets()->create([
            'position' => 2, 'name' => 'Retargeting', 'locations' => ['countries' => ['CA']],
            'budget' => 30, 'external_adset_id' => 'remote-set-2', 'status' => 'published',
        ]);
        $asset = Asset::create(['kind' => 'image', 'source' => 'upload', 'path' => 'assets/original.png']);
        $source->ads()->create([
            'ad_set_id' => $source->primaryAdSet->getKey(), 'asset_id' => $asset->getKey(),
            'headline' => 'Primary headline', 'primary_text' => 'Body', 'cta' => 'SHOP_NOW',
            'external_ad_id' => 'remote-ad', 'external_creative_id' => 'remote-creative', 'status' => 'published',
        ]);
        $source->ads()->create([
            'ad_set_id' => $second->getKey(), 'asset_id' => $asset->getKey(),
            'headline' => 'Second headline', 'primary_text' => 'Second body', 'cta' => 'SHOP_NOW', 'status' => 'published',
        ]);
        $set = TargetingSet::factory()->forCampaign($source)->create(['options' => ['geography_scope' => 'whole']]);
        $set->locations()->create(['operation' => 'include', 'kind' => 'country', 'country_code' => 'US', 'display_label' => 'United States']);
        app(Workspace::class)->produced($source);

        $result = $this->duplicate(['name' => 'Original copy']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $copy = Campaign::findOrFail($result['campaign_id']);
        $this->assertSame($source->getKey(), app(Workspace::class)->focus()?->getKey());
        $this->assertSame($copy->getKey(), (new Workspace($result['conversation']))->focus()?->getKey());
        $this->assertSame($result['conversation'], $copy->brief->conversation_id);
        $this->assertSame('Original copy', Conversation::findOrFail($result['conversation'])->title);
        $this->assertSame('Original copy', $copy->name);
        $this->assertSame('draft', $copy->status);
        $this->assertSame('75.00', $copy->budget);
        $this->assertSame('OUTCOME_SALES', $copy->objective);
        $this->assertSame('act_123', $copy->ad_account_id);
        $this->assertNull($copy->external_campaign_id);
        $this->assertNull($copy->external_ids);
        $this->assertNull($copy->published_state);
        $this->assertNotSame($source->brief_id, $copy->brief_id);
        $this->assertSame(['countries' => ['US']], $copy->adSets()->first()->locations);
        $this->assertSame(['age_min' => 25], $copy->adSets()->first()->audience);
        $this->assertSame('Retargeting', $copy->adSets()->get()[1]->name);
        $this->assertSame('30.00', $copy->adSets()->get()[1]->budget);
        $this->assertTrue($copy->adSets()->get()->every(fn ($adSet): bool => $adSet->status === 'draft' && $adSet->external_adset_id === null));
        $this->assertSame(['Primary headline', 'Second headline'], $copy->ads()->orderBy('id')->pluck('headline')->all());
        $this->assertSame([$asset->id, $asset->id], $copy->ads()->orderBy('id')->pluck('asset_id')->all());
        $this->assertTrue($copy->ads()->get()->every(fn ($ad): bool => $ad->status === 'draft' && $ad->external_ad_id === null && $ad->external_creative_id === null));
        $this->assertNotSame($set->getKey(), $copy->targetingSet->getKey());
        $this->assertSame($set->options, $copy->targetingSet->options);
        $this->assertSame(1, $copy->targetingSet->locations()->count());
        $this->assertSame('remote-campaign', $source->fresh()->external_campaign_id);
        $this->assertDatabaseHas('conversation_artifacts', [
            'conversation_id' => $result['conversation'], 'artifactable_id' => $asset->getKey(),
            'artifactable_type' => $asset->getMorphClass(),
        ]);
        Http::assertNothingSent();
    }

    public function test_linkedin_duplicate_preserves_resources_and_targeting_but_not_remote_ids(): void
    {
        $source = $this->sourceCampaign();
        $source->update(['platform' => 'linkedin', 'page_id' => '123', 'ad_account_id' => '556447014',
            'external_campaign_id' => '77', 'external_ids' => ['campaign_group_id' => '88'],
            'meta' => ['linkedin_setup' => ['campaign_group' => ['id' => 'new'], 'conversion' => ['id' => '55']]],
            'audience' => ['linkedin_facets' => ['seniorities' => ['urn:li:seniority:4']]]]);
        app(Workspace::class)->produced($source);

        $result = $this->duplicate(['name' => 'LinkedIn independent draft']);

        $this->assertTrue($result['ok']);
        $copy = Campaign::findOrFail($result['campaign_id']);
        $this->assertNull($copy->external_campaign_id);
        $this->assertNull($copy->external_ids);
        $this->assertSame('123', $copy->page_id);
        $this->assertSame(['urn:li:seniority:4'], $copy->audience['linkedin_facets']['seniorities']);
        $this->assertSame('55', $copy->meta['linkedin_setup']['conversion']['id']);
        Http::assertNothingSent();
    }

    public function test_inherited_brief_and_shared_place_resolution_are_independent(): void
    {
        $source = $this->sourceCampaign();
        $source->brief->update(['budget' => 42, 'budget_mode' => 'lifetime', 'locations' => ['countries' => ['US']]]);
        $briefSet = TargetingSet::factory()->create(['brief_id' => $source->brief_id, 'campaign_id' => null]);
        $briefSet->locations()->create(['operation' => 'include', 'kind' => 'country', 'country_code' => 'US', 'display_label' => 'United States']);
        $place = $briefSet->locations()->create(['operation' => 'include', 'kind' => 'city', 'country_code' => 'US', 'display_label' => 'Austin']);
        TargetingSet::factory()->forCampaign($source)->create([
            'mode' => 'inherit', 'options' => ['resolved_shared_places' => [$place->getKey() => 901]],
        ]);
        app(Workspace::class)->produced($source);

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

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $copy = Campaign::findOrFail($result['campaign_id']);
        $newPlace = $copy->brief->targetingSet->locations()->firstOrFail();
        $this->assertSame('Original (copy)', $copy->name);
        $this->assertSame('42.00', $copy->budget);
        $this->assertSame('lifetime', $copy->budget_mode);
        $this->assertSame(['US'], app(TargetingSelections::class)->countries($copy));
        $this->assertNotSame($place->getKey(), $newPlace->getKey());
        $this->assertSame([$newPlace->getKey() => 901], $copy->targetingSet->options['resolved_shared_places']);
        $source->brief->update(['budget' => 99, 'locations' => ['countries' => ['CA']]]);
        $this->assertSame('42.00', $copy->fresh()->budget);
        $this->assertSame(['US'], app(TargetingSelections::class)->countries($copy->fresh()));
        Http::assertNothingSent();
    }

    public function test_simple_imported_campaign_without_a_brief_can_be_copied(): void
    {
        $source = Campaign::create([
            'user_id' => auth()->id(), 'name' => 'Imported', 'platform' => 'meta',
            'status' => 'published', 'budget' => 20, 'locations' => ['countries' => ['US']],
            'external_campaign_id' => 'remote-campaign',
            'external_ids' => ['meta_custom_audience_criteria' => []],
        ]);

        $result = $this->duplicate(['campaign_id' => $source->getKey()]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $copy = Campaign::findOrFail($result['campaign_id']);
        $this->assertNotNull($copy->brief_id);
        $this->assertSame(['countries' => ['US']], $copy->locations);
        $this->assertSame('20.00', $copy->budget);
        $this->assertNull($copy->external_campaign_id);
        Http::assertNothingSent();
    }

    public function test_broken_shared_place_mapping_rolls_back_the_draft(): void
    {
        $source = $this->sourceCampaign();
        TargetingSet::factory()->forCampaign($source)->create([
            'options' => ['resolved_shared_places' => [9999 => 901]],
        ]);

        $result = $this->duplicate(['campaign_id' => $source->getKey()]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('shared place', $result['error']);
        $this->assertSame(1, Campaign::count());
        $this->assertSame(1, Brief::count());
        $this->assertSame(0, Conversation::count());
        Http::assertNothingSent();
    }

    public function test_campaign_drawer_button_creates_a_new_chat_for_the_visible_campaign(): void
    {
        $conversationId = 'duplicate-button-0001';
        $this->ownedConversation($conversationId);
        app(Workspace::class)->bindTo($conversationId);
        $source = $this->sourceCampaign();
        app(Workspace::class)->produced($source);

        $this->get(route('chat.show', ['conversation' => $conversationId]))
            ->assertOk()
            ->assertSee('data-duplicate-campaign="'.$source->getKey().'"', escape: false);

        $other = $this->sourceCampaign();
        $other->update(['name' => 'Another campaign']);
        app(Workspace::class)->produced($other);
        $this->postJson(route('chat.view'), [
            'conversation' => $conversationId,
            'campaign' => $source->getKey(),
        ])->assertOk()->assertSee('data-duplicate-campaign=\\"'.$source->getKey().'\\"', escape: false);

        $response = $this->postJson(route('chat.duplicate'), [
            'conversation' => $conversationId,
            'campaign' => $source->getKey(),
        ])->assertOk()->assertJsonPath('ok', true)->assertJsonPath('status', 'draft');

        $copy = Campaign::findOrFail($response->json('campaign_id'));
        $destinationId = $response->json('conversation');
        $this->assertNotSame($conversationId, $destinationId);
        $this->assertSame(route('chat.show', ['conversation' => $destinationId]), $response->json('url'));
        $this->assertSame('Original (copy)', $copy->name);
        $this->assertSame($other->getKey(), app(Workspace::class)->focus()?->getKey());
        $this->assertSame($copy->getKey(), (new Workspace($destinationId))->focus()?->getKey());
        $this->assertDatabaseCount('conversation_artifacts', 3);
        $this->assertDatabaseMissing('conversation_artifacts', [
            'conversation_id' => $conversationId,
            'artifactable_type' => $copy->getMorphClass(),
            'artifactable_id' => $copy->getKey(),
        ]);
        $this->assertDatabaseMissing('conversation_artifacts', [
            'conversation_id' => $destinationId,
            'artifactable_type' => $source->getMorphClass(),
            'artifactable_id' => $source->getKey(),
        ]);
        $this->assertDatabaseMissing('agent_conversation_messages', ['conversation_id' => $destinationId]);

        $this->get(route('chat.show', ['conversation' => $destinationId]))
            ->assertOk()
            ->assertSee('Original (copy)')
            ->assertSee('data-duplicate-campaign="'.$copy->getKey().'"', escape: false)
            ->assertDontSee('id="starterPrompts"', escape: false)
            ->assertDontSee('Another campaign');
        Http::assertNothingSent();
    }

    public function test_duplicate_button_rejects_a_campaign_outside_the_conversation(): void
    {
        $conversationId = 'duplicate-button-0002';
        $this->ownedConversation($conversationId);
        $source = $this->sourceCampaign();

        $this->postJson(route('chat.duplicate'), [
            'conversation' => $conversationId,
            'campaign' => $source->getKey(),
        ])->assertNotFound();

        $this->assertSame(1, Campaign::count());
        Http::assertNothingSent();
    }

    public function test_duplicate_button_sends_the_visible_campaign_and_opens_a_new_chat(): void
    {
        $command = sprintf(
            'node %s %s 2>&1',
            escapeshellarg(base_path('tests/js/duplicate-campaign.cjs')),
            escapeshellarg(public_path('assets/js/chat.js')),
        );
        $output = shell_exec($command);
        $result = json_decode((string) $output, true);

        $this->assertIsArray($result, 'Browser harness failed: '.(string) $output);
        $this->assertCount(1, $result['requests']);
        $this->assertStringEndsWith('/chat/duplicate', $result['requests'][0]['url']);
        $this->assertStringContainsString('name="conversation"', $result['requests'][0]['body']);
        $this->assertStringContainsString('name="campaign"', $result['requests'][0]['body']);
        $this->assertStringContainsString('7', $result['requests'][0]['body']);
        $this->assertSame('http://harness.test/chat?conversation=conversation-2', $result['url']);
    }

    public function test_foreign_campaign_and_unsupported_imported_targeting_are_refused(): void
    {
        $foreign = Campaign::create([
            'user_id' => User::factory()->create()->getKey(),
            'name' => 'Foreign', 'platform' => 'meta', 'status' => 'draft',
        ]);
        $this->assertFalse($this->duplicate(['campaign_id' => $foreign->getKey()])['ok']);
        $source = $this->sourceCampaign();
        $source->update(['external_ids' => ['meta_custom_audience_criteria' => ['123']]]);

        $result = $this->duplicate(['campaign_id' => $source->getKey()]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('cannot be copied faithfully', $result['error']);
        $this->assertSame(2, Campaign::count());
        $this->assertSame(1, Brief::count());
        $this->assertSame(0, Conversation::count());

        $source->update(['external_ids' => null]);
        $source->adSets()->create([
            'position' => 2, 'name' => 'Imported set',
            'locations' => ['google_location_criteria' => [['criterion_id' => 123]]],
        ]);
        $result = $this->duplicate(['campaign_id' => $source->getKey()]);
        $this->assertFalse($result['ok']);
        $this->assertSame(2, Campaign::count());
        Http::assertNothingSent();
    }

    private function sourceCampaign(): Campaign
    {
        $brief = Brief::factory()->create(['user_id' => auth()->id(), 'landing_url' => 'https://example.test/sale']);

        return Campaign::create([
            'user_id' => auth()->id(), 'brief_id' => $brief->getKey(),
            'name' => 'Original', 'platform' => 'meta', 'status' => 'draft',
        ]);
    }

    private function ownedConversation(string $id): void
    {
        DB::table('agent_conversations')->insert([
            'id' => $id,
            'participant_type' => auth()->user()->getMorphClass(),
            'participant_id' => auth()->id(),
            'title' => 'Duplicate test',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

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

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