<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * An ad account this login cannot advertise on is refused when it is chosen.
 *
 * Kaushal's 7 Oct campaign reached its first creative upload on
 * act_1184109403257239 and was refused there, by Meta: "To create or edit ads for
 * ad account 1184109403257239, contact an admin to get permission with an
 * Advertiser role or higher. Make sure that your API token includes the
 * ads_management permission." api_calls 542 and 543, campaign 13.
 *
 * By then the account, objective, special ad category, Page, pixel, conversion
 * event, bid strategy, bid amount, targeting, schedule and three ad variations had
 * all been answered against an account that could never have published any of it.
 *
 * The chooser was not at fault. list_ad_accounts reads me/adaccounts, which
 * returns 20 accounts, and every one of them has ADVERTISE: checked against the
 * live API, all 20 pass and that account is not among them. It got in because an
 * id can also be typed, which is the route Kaushal described taking, and a typed
 * id was verified for existence and for being active but never for whether we are
 * allowed to advertise on it. duplicate_campaign then copied it into the campaign
 * that failed.
 *
 * Meta says so up front in user_tasks and we were not asking. Live, on the three
 * accounts in play:
 *
 *   act_1184109403257239  SearchGPT        user_tasks absent      -> upload refused
 *   act_1950320145707342  TalkGPT          DRAFT ANALYZE ADVERTISE MANAGE
 *   act_1238155271384134  AutoAutomotive   DRAFT ANALYZE ADVERTISE MANAGE
 */
class AnAdAccountWeCannotAdvertiseOnIsRefusedAtChoiceTest extends TestCase
{
    use RefreshDatabase;

    private Campaign $campaign;

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

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

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['act_1184109403257239'],
        ]);

        $this->campaign = Campaign::create([
            'user_id' => $user->id,
            'name' => 'lucoscom (copy)',
            'platform' => 'meta',
            'status' => 'draft',
            'currency' => 'USD',
        ]);

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

    /** @param  list<string>|null  $tasks */
    private function accountReturning(?array $tasks): void
    {
        $body = [
            'id' => 'act_1184109403257239',
            'name' => 'SearchGPT',
            'account_status' => 1,
            'currency' => 'USD',
            'timezone_name' => 'PST8PDT',
        ];

        if ($tasks !== null) {
            $body['user_tasks'] = $tasks;
        }

        Http::fake(['*' => Http::response($body)]);
    }

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

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

    // --------------------------------------------------------- the refusal

    /** The account that actually failed: Meta omits user_tasks entirely. */
    public function test_an_account_with_no_role_is_refused(): void
    {
        $this->accountReturning(null);

        $result = $this->verify();

        $this->assertFalse($result['ok'], 'the account was accepted and would fail at the first upload');
        $this->assertStringContainsString('cannot create ads', $result['error']);
        $this->assertStringContainsString('Advertiser role', $result['error'], 'the buyer needs to know what to ask for');
    }

    /** And it is not written to the campaign, so nothing is built against it. */
    public function test_the_refused_account_is_not_recorded(): void
    {
        $this->accountReturning(null);

        $this->verify();

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

    /**
     * Read-only access is refused too, and the message says what we do have.
     *
     * DRAFT and ANALYZE are exactly the case where "the account is fine, it is
     * active, I can see its name" is most misleading.
     */
    public function test_read_only_access_is_refused_and_named(): void
    {
        $this->accountReturning(['DRAFT', 'ANALYZE']);

        $result = $this->verify();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('DRAFT, ANALYZE', $result['error']);
    }

    // ------------------------------------------------------ and the allowed

    /** The 20 real accounts all look like this. */
    public function test_an_account_we_can_advertise_on_is_accepted(): void
    {
        $this->accountReturning(['DRAFT', 'ANALYZE', 'ADVERTISE', 'MANAGE']);

        $result = $this->verify();

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');
        $this->assertSame('act_1184109403257239', $this->campaign->fresh()->ad_account_id);
    }

    /** MANAGE alone is enough: full control implies the lesser permission. */
    public function test_manage_without_advertise_is_enough(): void
    {
        $this->accountReturning(['MANAGE']);

        $this->assertTrue($this->verify()['ok'] ?? false);
    }

    /** ADVERTISE alone is enough, which is the minimum Meta needs to create ads. */
    public function test_advertise_alone_is_enough(): void
    {
        $this->accountReturning(['ADVERTISE']);

        $this->assertTrue($this->verify()['ok'] ?? false);
    }

    /** The field has to be asked for, or every account looks role-less. */
    public function test_user_tasks_is_requested_from_the_api(): void
    {
        $this->accountReturning(['ADVERTISE']);

        $this->verify();

        $asked = collect(Http::recorded())
            ->contains(fn (array $pair): bool => str_contains((string) $pair[0]->url(), 'user_tasks'));

        $this->assertTrue($asked, 'user_tasks was never requested, so the gate can only ever refuse');
    }
}
