<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\MarketingAgent;
use App\Agent\Workspace;
use App\Http\Controllers\ChatController;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * Clicking an option records the answer, without the model in the way.
 *
 * Every option already carries the value the platform accepts, and it never
 * left the browser: clicking put a sentence in the composer and the model had
 * to turn that back into an argument. Where the sentence contained the value
 * that worked. Where it did not, the model sometimes called the tool with no
 * argument, which re-offered the same question, so the click looked dead.
 *
 * Reproduced in the browser on 16 Sep on two steps. "Bid for highest volume"
 * left bidding empty and re-asked; the identical second click set it. "Use the
 * standard UTM tagging" did the same. The steps that worked first time all send
 * a phrase with the value inside it, like "Use ad account act_1418821929380936".
 */
class ClickedAnswerTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    private Campaign $campaign;

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

        $this->seedVerifiedCountries();

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['act_777'],
            'platforms.guardrails.budget_ceiling_currency' => 'USD',
            'platforms.guardrails.max_daily_budget' => 100,
        ]);

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

        DB::table('agent_conversations')->insert([
            'id' => 'conv-clicked-001',
            'participant_type' => $user->getMorphClass(),
            'participant_id' => $user->getKey(),
            'title' => 'Test',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-clicked-001');
        $workspace->ownedBy($user);

        $this->campaign = Campaign::create([
            'user_id' => $user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_TRAFFIC',
            'currency' => 'USD',
            'ad_account_id' => 'act_777',
        ]);

        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign);
    }

    private function click(string $field, string|array $value): bool
    {
        return app(Answers::class)->apply($field, $value);
    }

    /** @param array<string, mixed> $extra */
    private function rememberOffer(string $field, array $options, array $extra = []): void
    {
        app(Workspace::class)->rememberChoices([[
            'field' => $field,
            'options' => $options,
            ...$extra,
        ]]);
    }

    // --------------------------------------------- the two that were broken

    /** The click that silently did nothing until it was clicked twice. */
    public function test_choosing_a_bid_strategy_records_it(): void
    {
        $this->assertTrue($this->click('bid_strategy', 'LOWEST_COST_WITHOUT_CAP'));

        $this->assertSame('LOWEST_COST_WITHOUT_CAP', $this->campaign->fresh()->bid_strategy);
    }

    public function test_choosing_the_standard_tagging_records_it(): void
    {
        $this->assertTrue($this->click('utm', 'utm_source=facebook&utm_medium=paid_social'));

        $this->assertSame('utm_source=facebook&utm_medium=paid_social', $this->campaign->fresh()->utm);
    }

    // ------------------------------------------------------- answers of none

    /**
     * "No tracking" is an answer and has to survive as one.
     *
     * An empty string is how the tool tells "asked, and there is none" from
     * "never asked", so it cannot be dropped on the way through.
     */
    public function test_choosing_no_tracking_is_recorded_rather_than_ignored(): void
    {
        $this->assertTrue($this->click('utm', ''));

        $this->assertSame('', $this->campaign->fresh()->utm);
    }

    // ------------------------------------------------------- shapes

    /**
     * Countries first, because that is how the flow asks.
     *
     * Countries, placements and devices are offered as one group, and the
     * targeting tool will not save anything until it has a country: without one
     * it re-offers instead. Answering placements alone is not a state the
     * product can reach.
     */
    public function test_a_multi_select_arrives_as_a_list(): void
    {
        $this->click('countries', ['US']);

        $this->assertTrue($this->click('placements', ['facebook', 'instagram']));

        $this->assertSame(['facebook', 'instagram'], $this->campaign->fresh()->placements);
    }

    /** Devices are offered as one option carrying both, so they arrive comma joined. */
    public function test_all_devices_arrives_as_both(): void
    {
        $this->click('countries', ['US']);
        $this->assertTrue($this->click('devices', 'mobile,desktop'));

        $this->assertSame(['mobile', 'desktop'], $this->campaign->fresh()->audience['devices']);
    }

    /** Level and mode are one click, crossed into a single option. */
    public function test_the_budget_strategy_option_sets_both_level_and_mode(): void
    {
        $this->assertTrue($this->click('budget_strategy', 'campaign:lifetime'));

        $campaign = $this->campaign->fresh();

        $this->assertSame('campaign', $campaign->budget_level);
        $this->assertSame('lifetime', $campaign->budget_mode);
    }

    public function test_an_amount_arrives_as_a_number(): void
    {
        $this->assertTrue($this->click('budget_amount', '20'));

        $this->assertSame('20.00', $this->campaign->fresh()->budget);
    }

    // --------------------------------------------------------- falling back

    /**
     * Anything unrecognised leaves the turn exactly as it was.
     *
     * The message still reaches the model, which can still do the work, so a
     * question this does not know about degrades to the old behaviour rather
     * than failing.
     */
    public function test_an_unknown_question_is_left_to_the_model(): void
    {
        $this->assertFalse($this->click('something_we_never_ask', 'whatever'));
    }

    /** A tool that refuses is not reported as having answered. */
    public function test_a_refused_answer_is_not_reported_as_applied(): void
    {
        Http::fake(['*' => Http::response(['error' => ['message' => 'nope']], 400)]);

        $this->assertFalse($this->click('ad_account_id', 'act_999'));
    }

    // --------------------------------------------------- through the request

    /**
     * The whole path, as the browser walks it.
     *
     * The value is posted with the message and applied before the turn, so a
     * model that says nothing useful cannot lose the answer. Everything above
     * exercises the applier; this is the wiring that carries it there.
     */
    public function test_a_posted_answer_is_applied_even_when_the_model_does_nothing(): void
    {
        MarketingAgent::fake(['Right.']);
        $this->rememberOffer('bid_strategy', [['value' => 'LOWEST_COST_WITHOUT_CAP', 'label' => 'Highest volume']]);

        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'message' => 'Bid for highest volume',
            'answers' => [
                ['field' => 'bid_strategy', 'value' => 'LOWEST_COST_WITHOUT_CAP'],
            ],
        ])->assertOk();

        $this->assertSame('LOWEST_COST_WITHOUT_CAP', $this->campaign->fresh()->bid_strategy);
    }

    public function test_a_clicked_option_with_text_tells_the_model_it_is_already_recorded(): void
    {
        MarketingAgent::fake(['Right.']);
        $this->rememberOffer('bid_strategy', [['value' => 'LOWEST_COST_WITHOUT_CAP', 'label' => 'Highest volume']]);

        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'message' => 'Bid for highest volume',
            'answers' => [
                ['field' => 'bid_strategy', 'value' => 'LOWEST_COST_WITHOUT_CAP'],
            ],
        ])->assertOk();

        MarketingAgent::assertPrompted(fn ($prompt): bool => str_contains($prompt->prompt, 'Bid for highest volume')
            && str_contains($prompt->prompt, 'bid strategy: LOWEST_COST_WITHOUT_CAP')
            && str_contains($prompt->prompt, 'Do not submit these again'));
    }

    public function test_an_answer_from_a_replaced_card_is_not_applied(): void
    {
        MarketingAgent::fake(['Right.']);
        app(Workspace::class)->rememberChoices([[
            'field' => 'objective',
            'question' => 'Which objective?',
            'options' => [['value' => 'OUTCOME_SALES', 'label' => 'Sales']],
        ]]);

        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'answers' => [['field' => 'bid_strategy', 'value' => 'LOWEST_COST_WITHOUT_CAP']],
        ])->assertOk();

        $this->assertNull($this->campaign->fresh()->bid_strategy);
    }

    public function test_a_ui_answer_with_no_current_offer_is_not_applied(): void
    {
        MarketingAgent::fake(['Right.']);

        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'answers' => [['field' => 'bid_strategy', 'value' => 'LOWEST_COST_WITHOUT_CAP']],
        ])->assertOk();

        $this->assertNull($this->campaign->fresh()->bid_strategy);
    }

    public function test_answers_from_unrelated_cards_are_rejected_atomically(): void
    {
        MarketingAgent::fake(['Right.']);
        app(Workspace::class)->rememberChoices([[
            'field' => 'bid_strategy',
            'question' => 'Which bidding strategy?',
            'options' => [['value' => 'LOWEST_COST_WITHOUT_CAP', 'label' => 'Highest volume']],
        ]]);

        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'answers' => [
                ['field' => 'bid_strategy', 'value' => 'LOWEST_COST_WITHOUT_CAP'],
                ['field' => 'countries', 'value' => ['US']],
            ],
        ])->assertOk();

        $this->assertNull($this->campaign->fresh()->bid_strategy);
        $this->assertNull($this->campaign->fresh()->locations);
    }

    public function test_rejected_ui_answers_block_agent_tool_calls_for_that_turn(): void
    {
        app(Workspace::class)->rememberChoices([[
            'field' => 'objective',
            'question' => 'Which objective?',
            'options' => [['value' => 'OUTCOME_SALES', 'label' => 'Sales']],
        ]]);
        $controller = app(ChatController::class);
        $applied = (new \ReflectionMethod($controller, 'applyAnswers'))->invoke($controller, [[
            'field' => 'bid_strategy', 'value' => 'LOWEST_COST_WITHOUT_CAP',
        ]]);

        $this->assertFalse($applied[0]['applied']);
        $this->assertSame([], app(MarketingAgent::class)->tools());

        app(Workspace::class)->allowAgentToolCalls();
        $this->assertNotEmpty(app(MarketingAgent::class)->tools());
    }

    public function test_a_rejected_click_sent_with_a_message_is_named_to_the_model(): void
    {
        MarketingAgent::fake(['Right.']);
        $this->rememberOffer('objective', [['value' => 'OUTCOME_SALES', 'label' => 'Sales']]);

        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'message' => 'Use lowest cost.',
            'answers' => [['field' => 'bid_strategy', 'value' => 'LOWEST_COST_WITHOUT_CAP']],
        ])->assertOk();

        MarketingAgent::assertPrompted(fn ($prompt): bool => str_contains($prompt->prompt, 'Not accepted: bid strategy'));
    }

    /** @return array<string, array{0: string, 1: string, 2: bool}> */
    public static function stepRequests(): array
    {
        return [
            'united states is not a state' => ['Target the United States', 'location_scope', false],
            'placements is not a place' => ['Show the placements', 'location_scope', false],
            'marketing is not a market' => ['Marketing for a shoe shop', 'location_scope', false],
            'a city is' => ['Add a city please', 'location_scope', true],
            'a zip is' => ['Target zip 94107', 'location_scope', true],
            'a budget is' => ['Set the budget to 20', 'budget', true],
            'placements asked for' => ['Change the placements', 'placements', true],
            'unrelated word' => ['Sounds good', 'placements', false],
            'an existing campaign id asks for the account' => ['can you give name and objective for 120252613312230100 campaign', 'ad_account', true],
            'objective alone is not an account lookup' => ['What objective should this use?', 'ad_account', false],
            'a conversion rule is' => ['Use a different conversion rule', 'linkedin_conversion', true],
        ];
    }

    #[DataProvider('stepRequests')]
    public function test_a_step_is_only_requested_by_whole_words(string $message, string $step, bool $expected): void
    {
        $controller = app(ChatController::class);

        $this->assertSame(
            $expected,
            (new \ReflectionMethod($controller, 'userAskedForStep'))->invoke($controller, $message, $step),
        );
    }

    public function test_a_withdrawn_step_is_named_in_the_reply(): void
    {
        $controller = app(ChatController::class);
        (new \ReflectionProperty($controller, 'withdrawnSteps'))->setValue($controller, ['placements' => 'placements']);

        $reply = (new \ReflectionMethod($controller, 'withWithdrawalNote'))->invoke($controller, 'Here are the placements.', false);

        $this->assertStringContainsString('Please ignore any placements options', $reply);
    }

    public function test_a_reply_only_about_a_withdrawn_step_is_replaced_while_another_card_is_on_screen(): void
    {
        $controller = app(ChatController::class);
        (new \ReflectionProperty($controller, 'withdrawnSteps'))->setValue($controller, ['budget' => 'budget']);

        $reply = (new \ReflectionMethod($controller, 'withWithdrawalNote'))->invoke($controller, 'Choose a budget below, or type another amount.', true);

        $this->assertSame('Choose from the options below.', $reply);
    }

    public function test_only_the_sentences_about_a_withdrawn_step_are_dropped_while_another_card_is_on_screen(): void
    {
        $controller = app(ChatController::class);
        (new \ReflectionProperty($controller, 'withdrawnSteps'))->setValue($controller, ['linkedin_conversion' => 'conversion rule']);

        $reply = (new \ReflectionMethod($controller, 'withWithdrawalNote'))->invoke(
            $controller,
            "The audience remains the three selected titles. Choose the conversion rule shown on screen.\n\nReach is about 3.8M.",
            true,
        );

        $this->assertSame("The audience remains the three selected titles.\n\nReach is about 3.8M.", $reply);
    }

    public function test_a_reply_with_no_card_on_screen_keeps_the_withdrawal_note(): void
    {
        $controller = app(ChatController::class);
        (new \ReflectionProperty($controller, 'withdrawnSteps'))->setValue($controller, ['budget' => 'budget']);

        $reply = (new \ReflectionMethod($controller, 'withWithdrawalNote'))->invoke($controller, 'Saved the audience. Choose a budget below.', false);

        $this->assertStringStartsWith('Saved the audience. Choose a budget below.', $reply);
        $this->assertStringContainsString('Please ignore any budget options', $reply);
    }

    public function test_a_reply_that_is_only_the_steps_question_gets_no_withdrawal_note(): void
    {
        $controller = app(ChatController::class);
        (new \ReflectionProperty($controller, 'withdrawnSteps'))->setValue($controller, ['budget' => 'budget']);
        (new \ReflectionProperty($controller, 'steppedIn'))->setValue($controller, ['ask' => 'Where within the US?']);

        $reply = (new \ReflectionMethod($controller, 'withWithdrawalNote'))->invoke($controller, 'Where within the US?', true);

        $this->assertSame('Where within the US?', $reply);
    }

    public function test_a_withdrawal_note_is_not_added_when_the_reply_does_not_mention_that_step(): void
    {
        $controller = app(ChatController::class);
        (new \ReflectionProperty($controller, 'withdrawnSteps'))->setValue($controller, ['budget' => 'budget']);

        $reply = (new \ReflectionMethod($controller, 'withWithdrawalNote'))->invoke($controller, 'Right, let us pick your countries.', false);

        $this->assertSame('Right, let us pick your countries.', $reply);
    }

    public function test_an_offer_made_by_a_click_is_not_wiped_by_the_models_offer_for_another_step(): void
    {
        $choices = app(Choices::class);
        $option = [['value' => 'a', 'label' => 'A']];

        $choices->offer('location_list_review', 'Review', $option);
        $choices->pin();
        $choices->offer('budget_amount', 'Budget', $option);

        $this->assertSame(['location_list_review'], array_column($choices->all(), 'field'));
        $this->assertSame(['budget_amount'], $choices->ignored());
    }

    /** @return array<string, array{0: string, 1: string}> */
    public static function linkedInChoiceFields(): array
    {
        return [
            'conversion rule' => ['linkedin_conversion_id', 'linkedin_conversion'],
            'lead form' => ['linkedin_lead_form_id', 'linkedin_lead_form'],
        ];
    }

    /** An unmapped LinkedIn card dropped behind a pinned card left its sentence ("Choose an existing campaign group") over the location card. */
    #[DataProvider('linkedInChoiceFields')]
    public function test_a_linkedin_card_maps_to_its_flow_step(string $field, string $step): void
    {
        $controller = app(ChatController::class);

        $this->assertSame($step, (new \ReflectionMethod($controller, 'flowStepForChoice'))->invoke($controller, $field));
    }

    /** Several cities arrive nested; production raised "Array to string conversion" here. */
    public function test_a_nested_multi_city_answer_does_not_break_the_turn(): void
    {
        MarketingAgent::fake(['Right.', 'Right.']);
        $this->campaign->update(['locations' => ['countries' => ['US']]]);
        $answer = ['field' => 'location_search', 'value' => [
            'kind' => 'city', 'country_code' => 'US', 'catalog_places' => ['11', '12'],
        ]];
        $this->rememberOffer('location_search', [['value' => 'search', 'label' => 'Search']], [
            'search' => ['kind' => 'city', 'countries' => ['US'], 'catalog_places' => [], 'revision' => 0],
        ]);

        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'answers' => [$answer],
        ])->assertOk();

        MarketingAgent::assertPrompted(fn ($prompt): bool => str_contains($prompt->prompt, 'catalog_places: 11, 12')
            && str_contains($prompt->prompt, 'this was not accepted'));
    }

    /** Separate targeting cards persist their values one step at a time. */
    public function test_targeting_answers_post_one_current_step_at_a_time(): void
    {
        MarketingAgent::fake(['Right.', 'Right.', 'Right.']);

        $this->rememberOffer('countries', [['value' => 'US', 'label' => 'United States']]);

        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'message' => 'Target the United States.',
            'answers' => [['field' => 'countries', 'value' => ['US']]],
        ])->assertOk();

        $this->assertSame(['US'], $this->campaign->fresh()->locations['countries']);

        $this->rememberOffer('placements', [['value' => 'facebook', 'label' => 'Facebook']]);
        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'message' => 'Run on Facebook.',
            'answers' => [['field' => 'placements', 'value' => ['facebook']]],
        ])->assertOk();

        $this->assertSame(['facebook'], $this->campaign->fresh()->placements);

        $this->rememberOffer('devices', [['value' => 'mobile,desktop', 'label' => 'All devices']]);
        $this->post(route('chat.send'), [
            'conversation' => 'conv-clicked-001',
            'message' => 'Target both devices.',
            'answers' => [['field' => 'devices', 'value' => 'mobile,desktop']],
        ])->assertOk();

        $this->assertSame(['mobile', 'desktop'], $this->campaign->fresh()->audience['devices']);
    }

    // ------------------------------------------------------- the whole set

    /**
     * Every question this product puts on screen can be answered without the
     * model reading it back out of prose.
     *
     * Walked over the offers rather than a list written here, so a new question
     * cannot quietly reintroduce the guesswork.
     */
    public function test_every_offered_question_can_be_applied(): void
    {
        $answers = app(Answers::class);
        $choices = app(Choices::class);

        $choices->offer('bid_strategy', 'q', [['value' => 'x', 'label' => 'x']]);

        foreach ($choices->all() as $offer) {
            $this->assertTrue(
                $answers->handles($offer['field']),
                "question [{$offer['field']}] cannot be applied without the model",
            );
        }

        // The full set the flow offers today, so a missing one is a failure
        // here rather than a click that does nothing in the browser.
        foreach ([
            'platform', 'ad_account_id', 'objective', 'special_ad_categories',
            'page_id', 'pixel_id', 'budget_amount', 'budget_strategy', 'bid_strategy',
            'ends_at', 'countries', 'placements', 'devices', 'instagram_account_id',
            'utm', 'creative_ids',
        ] as $field) {
            $this->assertTrue($answers->handles($field), "question [{$field}] is not handled");
        }
    }
}
