<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * Highlights, then copy, then the variation choice: one question per step.
 *
 * Production showed the highlight question and the variation choice on screen
 * together, answered in one message, so the copy was written before the
 * highlight that was meant to shape it.
 */
class CopyFollowsTheHighlightTest extends TestCase
{
    use RefreshDatabase;

    private Campaign $campaign;

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

        $this->actingAs(User::factory()->create());
        $this->campaign = Campaign::create([
            'user_id' => auth()->id(), 'name' => 'Copy order', 'platform' => 'meta', 'status' => 'draft',
        ]);

        $workspace = app(Workspace::class);
        $workspace->bindTo('copy-order-chat');
        $workspace->produced($this->campaign);
    }

    private function writeCopy(array $extra = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($t) => $t->name() === 'campaign__write_ad_copy');

        return json_decode((string) $tool->handle(new Request([
            'ads' => array_map(fn (int $i): array => [
                'headline' => 'Headline '.$i, 'primary_text' => 'Body '.$i.'.', 'cta' => 'LEARN_MORE',
            ], [1, 2, 3]),
            ...$extra,
        ])), true);
    }

    private function fields(): array
    {
        return array_column(app(Choices::class)->all(), 'field');
    }

    public function test_copy_is_not_written_in_the_turn_the_highlight_question_is_shown(): void
    {
        app(Choices::class)->offerCopyEmphasis();

        $result = $this->writeCopy();

        $this->assertFalse($result['ok']);
        $this->assertSame(0, $this->campaign->ads()->count());
        $this->assertSame(['copy_emphasis'], $this->fields());
    }

    public function test_copy_waits_for_an_unanswered_highlight_from_the_last_turn(): void
    {
        app(Choices::class)->offerCopyEmphasis();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $this->assertFalse($this->writeCopy()['ok']);
        $this->assertSame(0, $this->campaign->ads()->count());
    }

    public function test_a_clicked_highlight_unlocks_copy_without_offering_choices_in_the_same_turn(): void
    {
        app(Choices::class)->offerCopyEmphasis();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $applied = app(Answers::class)->applyAll([['field' => 'copy_emphasis', 'value' => 'Customer Trust & Social Proof']]);
        $result = $this->writeCopy();

        $this->assertTrue($applied[0]['applied']);
        $this->assertTrue($result['ok'], json_encode($result));
        $this->assertSame(3, $this->campaign->ads()->count());
        $this->assertSame([], $this->fields());
    }

    public function test_a_typed_highlight_is_recorded_with_the_copy(): void
    {
        app(Choices::class)->offerCopyEmphasis();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $result = $this->writeCopy(['emphasis' => 'Free installation this month']);

        $this->assertTrue($result['ok'], json_encode($result));
        $this->assertSame(3, $this->campaign->ads()->count());
    }

    public function test_the_user_can_write_custom_copy_for_the_single_ad(): void
    {
        $asset = Asset::create([
            'owner_type' => auth()->user()->getMorphClass(), 'owner_id' => auth()->id(),
            'kind' => 'image', 'source' => 'generated', 'disk' => 'public', 'path' => 'custom.png',
            'original_name' => 'custom.png', 'mime' => 'image/png', 'bytes' => 1, 'checksum' => 'custom-copy',
        ]);
        $this->campaign->ads()->createMany([
            ['headline' => 'Old 1', 'primary_text' => 'Old body 1', 'cta' => 'LEARN_MORE', 'asset_id' => $asset->id],
            ['headline' => 'Old 2', 'primary_text' => 'Old body 2', 'cta' => 'LEARN_MORE'],
            ['headline' => 'Old 3', 'primary_text' => 'Old body 3', 'cta' => 'LEARN_MORE'],
        ]);
        $ads = $this->campaign->ads()->orderBy('id')->get();

        $applied = app(Answers::class)->applyAll([['field' => 'ad_copy_selection', 'value' => [
            'selection' => '__custom__::'.$ads[0]->id,
            'headline' => 'Security you can prove',
            'primary_text' => 'Prepare for SOC 2 with clear evidence and guided reviews.',
        ]]]);

        $this->assertTrue($applied[0]['applied']);
        $this->assertSame(1, $this->campaign->ads()->count());
        $custom = $this->campaign->ads()->firstOrFail();
        $this->assertSame('Security you can prove', $custom->headline);
        $this->assertSame('Prepare for SOC 2 with clear evidence and guided reviews.', $custom->primary_text);
        $this->assertSame($asset->id, $custom->asset_id);
    }
}
