<?php

namespace Tests\Feature;

use App\Agent\Choices;
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;

/**
 * Which countries this desk is offered as buttons.
 *
 * Pinned on purpose, which is unusual for a constant. The list is a product
 * decision about where this desk buys, and dropping an entry removes a button
 * without breaking anything else: the field still accepts any ISO code, the
 * publishers still send whatever is stored, and no other test reads it. India
 * was deleted on 24 Sep inside a rewrite of the docblock above it and nothing
 * noticed, which is exactly the shape of change this guards.
 *
 * A failure here is not a bug. It means somebody changed where this desk
 * advertises, and should say so in the same commit.
 */
class OfferedCountriesTest extends TestCase
{
    use RefreshDatabase;

    /** @return array{0: string, 1: array<string, mixed>} */
    private function offeredCountries(): array
    {
        $this->actingAs(User::factory()->create());

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-countries-0001');

        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_TRAFFIC',
        ]);

        $workspace->produced($campaign);

        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__set_targeting');

        $result = (string) $tool->handle(new Request([]));

        return [$result, collect(app(Choices::class)->all())->firstWhere('field', 'countries')];
    }

    public function test_the_desk_buys_these_countries(): void
    {
        [, $choice] = $this->offeredCountries();

        $this->assertNotNull($choice, 'No country question was offered at all.');

        $this->assertSame(
            ['US', 'GB', 'CA', 'AU', 'DE', 'IN'],
            array_column($choice['options'], 'value'),
        );
    }

    /**
     * The list is a shortlist, not a filter, and the question has to say so.
     *
     * Without that sentence the six buttons read as the only countries the
     * product supports, and a buyer who wants France has no way to know they
     * can simply type FR.
     */
    public function test_the_question_says_other_countries_can_be_typed(): void
    {
        [, $choice] = $this->offeredCountries();

        $this->assertStringContainsString('type others', $choice['question']);
    }
}
