<?php

namespace Tests\Feature;

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

/**
 * The button on the ad, offered from what the platform actually has.
 *
 * It used to arrive as free text beside the copy and be checked against one
 * hardcoded list of seven - Meta's - whatever the campaign ran on. LinkedIn was
 * therefore allowed BOOK_TRAVEL, which it has no button for, and refused APPLY,
 * REGISTER, REQUEST_DEMO and VIEW_QUOTE, four of its own ten. The failure landed
 * at publish as an enum error, after the copy had been agreed.
 *
 * What these pin: the list is the campaign's platform's, a button that platform
 * does not have is refused, a platform with no buttons says so instead of
 * offering seven, and the pick lands on every ad rather than one.
 */
class ChooseCallToActionTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

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

        MarketingAgent::fake(['Noted.']);

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

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-cta-0001');
        $workspace->ownedBy($this->user);
    }

    private function campaign(string $platform, int $ads = 3): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => ucfirst($platform).' campaign',
            'platform' => $platform,
            'status' => 'draft',
        ]);

        for ($i = 1; $i <= $ads; $i++) {
            $campaign->ads()->create([
                'headline' => "Headline {$i}",
                'primary_text' => "Body {$i}.",
                'cta' => 'LEARN_MORE',
            ]);
        }

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

        return $campaign->fresh();
    }

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

        $this->assertNotNull($tool, 'choose_call_to_action is not registered.');

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

    private function offered(): ?array
    {
        return collect(app(Choices::class)->all())->firstWhere('field', 'cta');
    }

    public function test_the_buttons_offered_are_the_platforms_own(): void
    {
        $this->campaign('meta');

        $this->assertTrue($this->runTool()['ok']);

        $values = array_column($this->offered()['options'], 'value');

        $this->assertContains('SHOP_NOW', $values);
        $this->assertContains('BOOK_TRAVEL', $values);
        $this->assertNotContains('REQUEST_DEMO', $values, 'REQUEST_DEMO is LinkedIn\'s, not Meta\'s.');
    }

    /** The reversal of the same question, which is the half that was broken. */
    public function test_linkedin_is_offered_linkedins_buttons(): void
    {
        $this->campaign('linkedin');

        $this->runTool();

        $values = array_column($this->offered()['options'], 'value');

        $this->assertContains('REQUEST_DEMO', $values);
        $this->assertContains('APPLY', $values);
        $this->assertNotContains('BOOK_TRAVEL', $values, 'LinkedIn has no Book Now button.');
    }

    /** A Google Search ad has no button, so there is nothing to offer. */
    public function test_a_platform_with_no_buttons_says_so_rather_than_offering_metas(): void
    {
        $this->campaign('google');

        $result = $this->runTool();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('no call to action', $result['error']);
        $this->assertNull($this->offered(), 'Nothing should be put on screen.');
    }

    public function test_an_unsupported_button_is_refused_with_the_supported_list(): void
    {
        $this->campaign('linkedin');

        $result = $this->runTool(['cta' => 'BOOK_TRAVEL']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('linkedin', $result['error']);
        $this->assertContains('REQUEST_DEMO', $result['supported']);
    }

    /**
     * The button describes the offer, not the variation.
     *
     * Three ads reading Shop Now, Learn More and Sign Up is not a test anybody
     * asked for, and the buyer who picks one means it for the campaign.
     */
    public function test_the_choice_lands_on_every_ad(): void
    {
        $campaign = $this->campaign('meta');

        $this->assertTrue($this->runTool(['cta' => 'SHOP_NOW'])['ok']);

        $this->assertSame(
            ['SHOP_NOW', 'SHOP_NOW', 'SHOP_NOW'],
            $campaign->ads()->pluck('cta')->all(),
        );
    }

    /** Clicking the button applies it here, not through the model. */
    public function test_the_clicked_button_applies_server_side(): void
    {
        $campaign = $this->campaign('meta');

        app(Answers::class)->applyAll([['field' => 'cta', 'value' => 'SIGN_UP']]);

        $this->assertSame('SIGN_UP', $campaign->ads()->value('cta'));
    }

    /** Offering is not applying. */
    public function test_offering_changes_nothing(): void
    {
        $campaign = $this->campaign('meta');

        $this->runTool();

        $this->assertSame('LEARN_MORE', $campaign->ads()->value('cta'));
    }

    /** What the ads carry now is marked, so the ordinary case stays one click. */
    public function test_the_current_button_is_marked(): void
    {
        $this->campaign('meta');

        $this->runTool();

        $current = collect($this->offered()['options'])->firstWhere('value', 'LEARN_MORE');

        $this->assertSame('Current', $current['badge'] ?? null);
    }

    public function test_leads_campaign_suggests_a_supported_learn_more_button(): void
    {
        $campaign = $this->campaign('meta');
        $campaign->update(['objective' => 'OUTCOME_LEADS']);

        $this->runTool();

        $learnMore = collect($this->offered()['options'])->firstWhere('value', 'LEARN_MORE');

        $this->assertSame('Suggested', $learnMore['badge'] ?? null);
        $this->assertStringContainsString('Leads', $learnMore['hint'] ?? '');
        $this->assertNotContains('GET_QUOTE', array_column($this->offered()['options'], 'value'));
    }

    /** There is nothing to set a button on before the copy exists. */
    public function test_it_asks_for_the_copy_first_when_there_are_no_ads(): void
    {
        $this->campaign('meta', ads: 0);

        $result = $this->runTool();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('ad copy first', $result['error']);
    }

    // -------------------------------------------------- ads already on Meta

    /**
     * A live ad keeps the button it launched with.
     *
     * The button is baked into the creative and Meta cannot reword one, so
     * writing the new button onto a live ad's row changed nothing on the
     * platform: the ad went on serving Learn More while our record said Shop
     * Now, the copy fingerprint drifted, and the campaign began reporting a
     * rebuild for a change that had never been made.
     */
    public function test_a_live_ad_keeps_the_button_it_launched_with(): void
    {
        $campaign = $this->campaign('meta', ads: 0);

        $live = $campaign->ads()->create([
            'headline' => 'Live one', 'primary_text' => 'Running.', 'cta' => 'LEARN_MORE',
            'external_ad_id' => 'ad-1', 'status' => 'published',
        ]);
        $draft = $campaign->ads()->create([
            'headline' => 'Draft one', 'primary_text' => 'Not yet.', 'cta' => 'LEARN_MORE',
        ]);

        $result = $this->runTool(['cta' => 'SHOP_NOW']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('LEARN_MORE', $live->fresh()->cta, 'the live ad\'s row was rewritten');
        $this->assertSame('SHOP_NOW', $draft->fresh()->cta, 'the draft was not updated');
    }

    /** And the reply says which ads were left, so the chat does not claim them. */
    public function test_it_names_the_live_ads_it_left_alone(): void
    {
        $campaign = $this->campaign('meta', ads: 0);

        $campaign->ads()->create([
            'headline' => 'Live one', 'primary_text' => 'Running.', 'cta' => 'LEARN_MORE',
            'external_ad_id' => 'ad-1', 'status' => 'published',
        ]);
        $campaign->ads()->create(['headline' => 'Draft', 'primary_text' => 'x.', 'cta' => 'LEARN_MORE']);

        $result = $this->runTool(['cta' => 'SHOP_NOW']);

        $this->assertSame(['ad-1'], $result['already_live']);
        $this->assertSame(1, $result['ads_updated']);
        $this->assertStringContainsString('edit_entity', $result['note']);
    }

    /** With nothing but live ads there is no half-measure to report as success. */
    public function test_a_fully_live_campaign_is_refused_and_points_at_edit_entity(): void
    {
        $campaign = $this->campaign('meta', ads: 0);

        $campaign->ads()->create([
            'headline' => 'Live one', 'primary_text' => 'Running.', 'cta' => 'LEARN_MORE',
            'external_ad_id' => 'ad-1', 'status' => 'published',
        ]);

        $result = $this->runTool(['cta' => 'SHOP_NOW']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('already live', $result['error']);
        $this->assertStringContainsString('edit_entity', $result['note']);
        $this->assertSame('LEARN_MORE', $campaign->ads()->first()->cta);
    }

    /** The ordinary draft case is untouched by all of the above. */
    public function test_a_draft_campaign_still_has_every_ad_set(): void
    {
        $campaign = $this->campaign('meta');

        $result = $this->runTool(['cta' => 'SHOP_NOW']);

        $this->assertTrue($result['ok']);
        $this->assertSame(3, $result['ads_updated']);
        $this->assertArrayNotHasKey('already_live', $result);
        $this->assertSame([3, 0], [
            $campaign->ads()->where('cta', 'SHOP_NOW')->count(),
            $campaign->ads()->where('cta', '!=', 'SHOP_NOW')->count(),
        ]);
    }

    /**
     * Re-picking the button the ads already carry still succeeds.
     *
     * The live-ad refusal first keyed on how many rows the update touched.
     * MariaDB reports rows changed rather than rows matched, so setting SHOP_NOW
     * on ads that already said SHOP_NOW reported nothing updated and read as
     * every ad being live - on a campaign with no live ads at all.
     *
     * This test cannot fail on the defect it is named for: the suite runs on
     * SQLite in memory, which reports rows matched. It was confirmed against
     * the real MariaDB by hand, and the tool now counts the ads it applies to
     * instead of trusting either engine. Kept because it pins the behaviour
     * the engines disagreed about.
     */
    public function test_choosing_the_button_the_ads_already_carry_is_not_refused(): void
    {
        $campaign = $this->campaign('meta', ads: 0);

        $campaign->ads()->create(['headline' => 'One', 'primary_text' => 'x.', 'cta' => 'SHOP_NOW']);

        $result = $this->runTool(['cta' => 'SHOP_NOW']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(1, $result['ads_updated']);
    }
}
