<?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;

/**
 * The bid cap question promised typing and offered five buttons.
 *
 * Same defect as the budget amount, in the tool next to it, and this one had
 * been reported twice. offerTargetCost()'s own docblock is headed "Target costs
 * worth one click, with typing still open" and both questions it asks end in
 * "Pick one or type any amount". Neither was true: Choices::offer() draws the
 * Other field from allowOther, the call did not pass it, and 1, 2, 5, 10 and 25
 * were the only things on screen. A cap of 1.50, or of 40, read as unavailable.
 *
 * Worse away from USD. The ladder is the same five integers whatever the account
 * is billed in, which is a usable spread of dollars and a meaningless one of yen,
 * so the further an account sits from USD the more certain it is that the number
 * the buyer wants is not on screen.
 *
 * The strategy question above it stays closed, for the reason the budget strategy
 * question does: COST_CAP and LOWEST_COST_WITH_BID_CAP are an enum Meta defines
 * and a typed answer could only be a wrong one.
 */
class ABidCapCanBeTypedRatherThanPickedTest extends TestCase
{
    use RefreshDatabase;

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

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

    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Meta campaign',
            'platform' => 'meta',
            'status' => 'draft',
            'currency' => 'USD',
            ...$attributes,
        ]);

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

        return $campaign;
    }

    /** @return array<string,mixed> */
    private function setBidding(array $arguments = []): array
    {
        $result = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__set_bidding')
            ->handle(new Request($arguments));

        return json_decode((string) $result, true);
    }

    /** @return array<string,mixed>|null */
    private function offerFor(string $field): ?array
    {
        return collect(app(Choices::class)->all())->first(fn (array $o): bool => $o['field'] === $field);
    }

    // ------------------------------------------------- a cap of your own

    /** The defect, under a bid cap: this is the maximum Mohsin asked to type. */
    public function test_a_bid_cap_can_be_typed(): void
    {
        $this->campaign(['bid_strategy' => 'LOWEST_COST_WITH_BID_CAP']);

        $this->setBidding(['strategy' => 'LOWEST_COST_WITH_BID_CAP']);

        $offer = $this->offerFor('bid_amount');

        $this->assertNotNull($offer, 'no amounts were offered at all');
        $this->assertTrue(
            $offer['allow_other'] ?? false,
            'the question says "or type any amount" and nothing on screen allows it',
        );
    }

    /** And under a cost cap, where the same ladder is shown. */
    public function test_a_target_cost_can_be_typed(): void
    {
        $this->campaign(['bid_strategy' => 'COST_CAP']);

        $this->setBidding(['strategy' => 'COST_CAP']);

        $this->assertTrue($this->offerFor('bid_amount')['allow_other'] ?? false);
    }

    /** The rungs are still there: typing is the escape, not the only route. */
    public function test_the_suggested_amounts_are_still_offered(): void
    {
        $this->campaign(['bid_strategy' => 'COST_CAP']);

        $this->setBidding(['strategy' => 'COST_CAP']);

        $this->assertNotEmpty($this->offerFor('bid_amount')['options'] ?? []);
    }

    /**
     * The strategy question stays closed.
     *
     * Meta defines the strategies, so an answer that is not one of them is not a
     * preference, it is a value that fails at publish.
     */
    public function test_the_strategy_question_does_not_take_a_free_answer(): void
    {
        $this->campaign();

        $this->setBidding();

        $strategy = $this->offerFor('bid_strategy');

        $this->assertNotNull($strategy, 'the strategy should still be asked');
        $this->assertFalse($strategy['allow_other'] ?? false);
    }
}
