<?php

namespace Tests\Feature;

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

/**
 * A buyer can ask what is in a campaign, and get ids back.
 *
 * Nothing could answer this before. list_campaigns gives one line per campaign
 * on an account; open_campaign adopts one and reports a count of its other ad
 * sets and nothing else; review_published_location reads live ad sets but
 * surfaces only their geo targeting. Ad set and ad ids reached the chat in
 * exactly one place - an error branch in add_ads - so nobody could ask what
 * their campaign contained, and the model had no id with which to act on any
 * part of it.
 *
 * Graph had no ad reader at all: it could create an ad and delete one, and not
 * list them. CampaignImporter does not import ads either, so for any campaign
 * this product did not build, the ads were simply unreachable.
 */
class CampaignStructureCanBeListedTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

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

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

        app(Workspace::class)->bindTo('conv-structure');
        app(Workspace::class)->ownedBy($this->user);
    }

    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
            'external_campaign_id' => '120252047635070626',
            ...$attributes,
        ]);

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

        return $campaign;
    }

    /** Order matters: a wildcard ads pattern would also match the adsets edge. */
    private function fakeMeta(array $adSets, array $ads): void
    {
        Http::fake([
            '*/adsets*' => Http::response(['data' => $adSets]),
            '*/ads*' => Http::response(['data' => $ads]),
        ]);
    }

    private function structure(array $arguments = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t): bool => $t->name() === 'campaign__list_campaign_structure');

        $this->assertNotNull($tool, 'campaign__list_campaign_structure is not registered');
        /** @var NamespacedTool $tool */

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    // ------------------------------------------------------------- the answer

    public function test_it_returns_counts_ids_names_and_statuses(): void
    {
        $this->campaign();
        $this->fakeMeta(
            [
                ['id' => 'adset-1', 'name' => 'US mobile', 'status' => 'ACTIVE', 'daily_budget' => '2500', 'optimization_goal' => 'LINK_CLICKS'],
                ['id' => 'adset-2', 'name' => 'UK test', 'status' => 'PAUSED'],
            ],
            [
                ['id' => 'ad-1', 'name' => 'Winter Sale - ad 1', 'status' => 'ACTIVE', 'effective_status' => 'ACTIVE', 'adset_id' => 'adset-1', 'creative' => ['title' => 'Everything reduced']],
                ['id' => 'ad-2', 'name' => 'Winter Sale - ad 2', 'status' => 'PAUSED', 'effective_status' => 'ADSET_PAUSED', 'adset_id' => 'adset-2'],
            ],
        );

        $result = $this->structure();

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(2, $result['counts']['ad_sets']);
        $this->assertSame(2, $result['counts']['ads']);
        $this->assertSame(['adset-1', 'adset-2'], array_column($result['ad_sets'], 'id'));
        $this->assertSame(['US mobile', 'UK test'], array_column($result['ad_sets'], 'name'));
        $this->assertSame(['ACTIVE', 'PAUSED'], array_column($result['ad_sets'], 'status'));
        $this->assertSame(['ad-1', 'ad-2'], array_column($result['ads'], 'id'));
        $this->assertSame('Everything reduced', $result['ads'][0]['headline']);
    }

    public function test_each_ad_includes_the_copy_and_url_stored_on_the_creative(): void
    {
        $this->campaign();
        $this->fakeMeta(
            [['id' => 'adset-1', 'name' => 'US mobile', 'status' => 'ACTIVE']],
            [[
                'id' => 'ad-1',
                'name' => 'Wireless',
                'status' => 'ACTIVE',
                'effective_status' => 'ACTIVE',
                'adset_id' => 'adset-1',
                'creative' => [
                    'title' => 'Compare Wireless Plans',
                    'body' => '',
                    'object_story_spec' => [
                        'link_data' => [
                            'message' => 'See the plans side by side.',
                            'name' => 'Compare Wireless Plans',
                            'description' => 'No annual contract.',
                            'link' => 'https://example.com/wireless',
                        ],
                    ],
                ],
            ]],
        );

        $ad = $this->structure()['ads'][0];

        $this->assertSame('See the plans side by side.', $ad['primary_text']);
        $this->assertSame('Compare Wireless Plans', $ad['headline']);
        $this->assertSame('No annual contract.', $ad['description']);
        $this->assertSame('https://example.com/wireless', $ad['url']);
        Http::assertSent(fn ($request): bool => str_contains($request->url(), '/ads')
            && str_contains((string) $request->data()['fields'], 'object_story_spec')
            && str_contains((string) $request->data()['fields'], 'asset_feed_spec')
            && str_contains((string) $request->data()['fields'], 'link_url'));
    }

    public function test_all_copy_url_and_cta_variants_are_returned_without_hiding_asset_feed_values(): void
    {
        $this->campaign();
        $this->fakeMeta([], [[
            'id' => 'ad-1',
            'creative' => [
                'body' => 'Story body', 'title' => 'Story headline', 'call_to_action_type' => 'LEARN_MORE',
                'object_story_spec' => ['link_data' => ['link' => 'https://example.com/story']],
                'asset_feed_spec' => [
                    'bodies' => [['text' => 'Feed body', 'adlabels' => [['name' => 'mobile']]]],
                    'titles' => [['text' => 'Feed headline']],
                    'descriptions' => [['text' => 'Feed description']],
                    'link_urls' => [['website_url' => 'https://example.com/feed?a={{ad.id}}']],
                    'call_to_action_types' => ['GET_QUOTE'],
                    'call_to_actions' => [['type' => 'SIGN_UP', 'value' => ['link' => 'https://example.com/signup']]],
                    'asset_customization_rules' => [['body_label' => ['name' => 'mobile']]],
                ],
            ],
        ], ['id' => 'ad-2']]);

        $result = $this->structure();
        $ad = $result['ads'][0];
        $this->assertSame(['Story body', 'Feed body'], $ad['primary_texts']);
        $this->assertSame(['Story headline', 'Feed headline'], $ad['headlines']);
        $this->assertSame(['Feed description'], $ad['descriptions']);
        $this->assertSame(['https://example.com/story', 'https://example.com/feed?a={{ad.id}}', 'https://example.com/signup'], $ad['urls']);
        $this->assertSame(['LEARN_MORE', 'GET_QUOTE', 'SIGN_UP'], $ad['ctas']);
        $this->assertSame('', $ad['url'], 'Multiple links must not look like a single campaign destination.');
        $this->assertSame('mobile', $ad['copy_assets']['bodies'][0]['adlabels'][0]['name']);
        $this->assertSame('not_returned', $result['ads'][1]['creative_read_status']);
    }

    public function test_meta_ad_and_ad_set_pages_have_independent_continuation_tokens(): void
    {
        $this->campaign();
        Http::fake([
            '*/adsets?*' => Http::sequence()
                ->push(['data' => [['id' => 'set-1']], 'paging' => ['next' => 'https://graph.facebook.com/next', 'cursors' => ['after' => 'sets-next']]])
                ->push(['data' => [['id' => 'set-2']]]),
            '*/ads?*' => Http::sequence()
                ->push(['data' => [['id' => 'ad-1']], 'paging' => ['next' => 'https://graph.facebook.com/next', 'cursors' => ['after' => 'ads-next']]])
                ->push(['data' => [['id' => 'ad-2']]]),
        ]);

        $first = $this->structure();
        $this->assertTrue($first['truncated']);
        $this->assertSame('returned_page', $first['counts_scope']);
        $second = $this->structure(['page_token' => $first['next_page_token'], 'ad_sets_page_token' => $first['next_ad_sets_page_token']]);
        $this->assertFalse($second['truncated']);
        $this->assertSame('ad-2', $second['ads'][0]['id']);
        $this->assertSame('set-2', $second['ad_sets'][0]['id']);
        Http::assertSent(fn ($request): bool => str_contains($request->url(), '/ads?') && ($request['after'] ?? null) === 'ads-next');
        Http::assertSent(fn ($request): bool => str_contains($request->url(), '/adsets?') && ($request['after'] ?? null) === 'sets-next');
    }

    public function test_a_destination_stored_only_on_an_asset_cta_is_not_lost(): void
    {
        $this->campaign();
        $this->fakeMeta([], [['id' => 'ad-1', 'creative' => ['asset_feed_spec' => [
            'call_to_actions' => [['type' => 'GET_QUOTE', 'value' => ['link' => 'https://example.com/quote']]],
        ]]]]);

        $ad = $this->structure()['ads'][0];
        $this->assertSame(['https://example.com/quote'], $ad['urls']);
        $this->assertSame(['GET_QUOTE'], $ad['ctas']);
    }

    /**
     * effective_status is carried as well as status.
     *
     * They disagree in the case that matters: an ad set to ACTIVE under a paused
     * ad set shows nothing, and reporting only status would call it running.
     */
    public function test_it_distinguishes_status_from_effective_status(): void
    {
        $this->campaign();
        $this->fakeMeta(
            [['id' => 'adset-1', 'name' => 'Paused set', 'status' => 'PAUSED']],
            [['id' => 'ad-1', 'name' => 'ad 1', 'status' => 'ACTIVE', 'effective_status' => 'ADSET_PAUSED', 'adset_id' => 'adset-1']],
        );

        $ad = $this->structure()['ads'][0];

        $this->assertSame('ACTIVE', $ad['status']);
        $this->assertSame('ADSET_PAUSED', $ad['effective_status']);
    }

    /** Each ad set carries how many ads are under it, so a count needs no second call. */
    public function test_each_ad_set_reports_its_own_ad_count(): void
    {
        $this->campaign();
        $this->fakeMeta(
            [['id' => 'adset-1', 'name' => 'One'], ['id' => 'adset-2', 'name' => 'Two']],
            [
                ['id' => 'ad-1', 'adset_id' => 'adset-1'],
                ['id' => 'ad-2', 'adset_id' => 'adset-1'],
                ['id' => 'ad-3', 'adset_id' => 'adset-2'],
            ],
        );

        $result = $this->structure();

        $this->assertSame([2, 1], array_column($result['ad_sets'], 'ads'));
        $this->assertSame(3, $result['counts']['ads']);
    }

    /** An explicit ad set narrows the ad read to that one parent. */
    public function test_an_ad_set_id_narrows_the_ads_read(): void
    {
        $this->campaign();
        $this->fakeMeta([['id' => 'adset-1']], [['id' => 'ad-1', 'adset_id' => 'adset-1']]);

        $this->structure(['ad_set_id' => 'adset-1']);

        Http::assertSent(fn ($request): bool => str_contains($request->url(), 'adset-1/ads'));
    }

    // ------------------------------------------------------------ the refusals

    /** A draft has nothing on the platform to list, and that is not a failure. */
    public function test_an_unpublished_campaign_is_refused_without_a_call(): void
    {
        $this->campaign(['external_campaign_id' => null, 'status' => 'draft']);

        Http::fake();

        $result = $this->structure();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not been published', $result['error']);
        Http::assertNothingSent();
    }

    public function test_no_campaign_in_focus_is_refused_without_a_call(): void
    {
        Http::fake();

        $result = $this->structure();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('No campaign is in focus', $result['error']);
        Http::assertNothingSent();
    }

    /**
     * A platform that cannot be listed is named rather than answered with an
     * empty structure.
     *
     * This asked about Google, which has since gained a read of its own - see
     * AGoogleCampaignCanBeListedTest. LinkedIn carried the case next and has
     * since grown its own branch here, so the stand-in has moved again. The
     * thing being tested was never about one platform: it is that "we cannot
     * look" is said out loud instead of being returned as "there is nothing in
     * it", which are opposite answers for the buyer.
     */
    public function test_a_platform_that_cannot_be_listed_says_so_rather_than_returning_nothing(): void
    {
        $this->campaign(['platform' => 'tiktok', 'ad_account_id' => '3460855874']);

        Http::fake();

        $result = $this->structure();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Tiktok', $result['error']);
        Http::assertNothingSent();
    }

    /**
     * A platform error must not read as an empty campaign.
     *
     * "It has no ad sets" and "Meta would not tell us" lead to opposite next
     * actions, and the first one invites the model to offer a rebuild.
     */
    public function test_a_platform_error_is_not_an_empty_campaign(): void
    {
        $this->campaign();

        Http::fake(['*' => Http::response(['error' => ['message' => 'Unsupported get request']], 400)]);

        $result = $this->structure();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not an empty campaign', $result['note']);
    }

    /** A genuinely empty campaign says so, and tells the model not to offer actions. */
    public function test_an_empty_campaign_is_reported_as_empty(): void
    {
        $this->campaign();
        $this->fakeMeta([], []);

        $result = $this->structure();

        $this->assertTrue($result['ok']);
        $this->assertSame(0, $result['counts']['ad_sets']);
        $this->assertStringContainsString('no ad sets and no ads', $result['note']);
    }

    /** The read is fresh, so a change made in Ads Manager shows up. */
    public function test_the_read_bypasses_the_request_memo(): void
    {
        $this->campaign();
        $this->fakeMeta([['id' => 'adset-1']], [['id' => 'ad-1', 'adset_id' => 'adset-1']]);

        $this->structure();
        $this->structure();

        // Two invocations, two reads of each edge: nothing is served from the
        // per-request memo, because the point is current platform state.
        $this->assertGreaterThanOrEqual(4, count(Http::recorded()));
    }
}
