<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Tools\OfferClarification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

class OfferClarificationTest extends TestCase
{
    use RefreshDatabase;

    public function test_budget_ambiguity_is_offered_as_two_answers_plus_composer_other(): void
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'workspace__offer_clarification');
        $this->assertNotNull($tool);

        $result = json_decode((string) $tool->handle(new Request([
            'question' => 'Does $10 cover the whole 14-day campaign, or each day?',
            'options' => ['$10 total for 14 days', '$10 per day for 14 days'],
        ])), true);

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

        $choice = app(Choices::class)->all()[0];
        $this->assertSame('clarification', $choice['field']);
        $this->assertSame('Does $10 cover the whole 14-day campaign, or each day?', $choice['question']);
        $this->assertSame(['$10 total for 14 days', '$10 per day for 14 days'], array_column($choice['options'], 'label'));
        $this->assertTrue($choice['allow_other']);
        $this->assertTrue($choice['other_in_composer']);
    }

    public function test_a_duplicated_answer_does_not_create_a_question(): void
    {
        $result = json_decode((string) app(OfferClarification::class)->handle(new Request([
            'question' => 'Which budget?',
            'options' => ['$10 daily', '$10 daily'],
        ])), true);

        $this->assertFalse($result['ok']);
        $this->assertSame([], app(Choices::class)->all());
    }

    public function test_other_is_added_by_the_renderer_only_once(): void
    {
        $result = json_decode((string) app(OfferClarification::class)->handle(new Request([
            'question' => 'Which budget?',
            'options' => ['$10 daily', 'Other'],
        ])), true);

        $this->assertFalse($result['ok']);
        $this->assertSame([], app(Choices::class)->all());
    }
}
