<?php

namespace Tests\Feature;

use App\Agent\Instructions;
use App\Agent\Workspace;
use App\Campaigns\Platforms\MetaRules;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * Nine tools nobody could reach, a bid cap nobody could type, and one duplicated
 * query parameter.
 *
 * All three came out of the same feedback round, and the first is the one worth
 * naming properly. Roughly a third of what the team asked for already existed:
 * create_pixel, duplicate_campaign, choose_call_to_action, choose_audience_list,
 * review_audience_sizing, choose_ad_copy, set_tracking, review_assets and
 * split_budget are all registered in AgentServiceProvider and all work.
 *
 * None of them is in MetaRules::steps(), which is what NEXT STEP reads, and none
 * was named anywhere in the system prompt. So the flow never raised them, the
 * user was never offered them, and "we need the ability to create a pixel" was
 * filed against a tool that had been shipped. Tool schemas alone were not
 * enough: the model follows NEXT STEP, and NEXT STEP had nothing to say.
 *
 * Asserted on the built prompt rather than on a list of strings in a config,
 * because the failure was specifically that the prompt did not mention them. A
 * test that reads the same constant the prompt reads would have passed
 * throughout.
 */
class WhatTheStepListNeverOffersTest extends TestCase
{
    use RefreshDatabase;

    private function promptForADraft(): string
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $brief = Brief::create([
            'user_id' => $user->id,
            'conversation_id' => 'conv-capabilities',
            'landing_url' => 'https://attestpath.com/soc2',
        ]);

        $campaign = Campaign::create([
            'user_id' => $user->id,
            'brief_id' => $brief->id,
            'name' => 'Attestpath SOC 2',
            'platform' => 'meta',
            'status' => 'draft',
            'currency' => 'USD',
        ]);

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-capabilities');
        $workspace->ownedBy($user);
        $workspace->produced($campaign);
        $workspace->focusOn($campaign->fresh());

        return app(Instructions::class)->build();
    }

    // --------------------------------------------- the tools are reachable

    public function test_the_prompt_names_every_tool_no_step_reaches(): void
    {
        $prompt = $this->promptForADraft();

        $unreachable = [
            'create_pixel',
            'duplicate_campaign',
            'choose_call_to_action',
            'choose_audience_list',
            'review_audience_sizing',
            'choose_ad_copy',
            'set_tracking',
            'review_assets',
            'split_budget',
        ];

        foreach ($unreachable as $tool) {
            $this->assertStringContainsString(
                $tool,
                $prompt,
                $tool.' is registered but the prompt never mentions it, so nothing will call it',
            );
        }
    }

    /**
     * None of them became a step, which would have been the wrong fix.
     *
     * Making them steps lengthens the one path every buyer walks to reach a first
     * publish, and the same feedback round asked for fewer questions at a time,
     * not more. They are capabilities to volunteer, not questions to ask.
     */
    public function test_they_were_not_added_to_the_launch_flow(): void
    {
        $tools = collect(app(MetaRules::class)->steps())->pluck('tool');

        foreach (['create_pixel', 'duplicate_campaign', 'split_budget', 'choose_ad_copy'] as $tool) {
            $this->assertFalse($tools->contains($tool), $tool.' became a mandatory step');
        }
    }

    /** And the prompt says why they will not appear in NEXT STEP. */
    public function test_the_prompt_explains_that_next_step_will_not_raise_them(): void
    {
        $this->assertStringContainsString(
            'NEXT STEP never asks for',
            $this->promptForADraft(),
        );
    }

    // ------------------------------------------------------- the UTM option

    /**
     * "Standard, plus placement" must not send utm_term twice.
     *
     * The standard string ends in utm_term={{ad.id}} and this appended
     * &utm_term={{placement}} to it. Nothing in the chain treats a repeated key
     * as an error: Meta substitutes both, the browser sends both, and whatever
     * reads the URL keeps one of them. On last-wins the ad id is the one lost, so
     * the option sold as adding a dimension quietly dropped one.
     */
    public function test_the_placement_option_does_not_repeat_utm_term(): void
    {
        $options = collect(app(MetaRules::class)->trackingOptions());
        $placement = $options->firstWhere('label', 'Standard, plus placement');

        $this->assertNotNull($placement, 'the placement option has gone');

        parse_str((string) parse_url('https://x.test/?'.ltrim((string) $placement['value'], '?'), PHP_URL_QUERY), $parsed);

        $this->assertSame(
            1,
            substr_count((string) $placement['value'], 'utm_term='),
            'utm_term appears more than once: '.$placement['value'],
        );
        $this->assertArrayHasKey('utm_placement', $parsed, 'placement is not recorded anywhere');
        $this->assertSame('{{placement}}', $parsed['utm_placement']);
    }

    /** The ad id survives, which is the thing the duplicate was costing. */
    public function test_the_ad_id_is_still_in_the_placement_option(): void
    {
        $placement = collect(app(MetaRules::class)->trackingOptions())
            ->firstWhere('label', 'Standard, plus placement');

        parse_str((string) parse_url('https://x.test/?'.ltrim((string) $placement['value'], '?'), PHP_URL_QUERY), $parsed);

        $this->assertSame('{{ad.id}}', $parsed['utm_term'] ?? null);
    }

    /** Standard tagging itself is untouched. */
    public function test_standard_tagging_is_unchanged(): void
    {
        $standard = collect(app(MetaRules::class)->trackingOptions())
            ->firstWhere('label', 'Standard tagging');

        $this->assertSame(config('platforms.tracking.default_utm'), $standard['value']);
    }
}
