<?php

namespace Tests\Feature;

use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Laravel\Ai\Models\Conversation;
use Tests\TestCase;

/**
 * A click in the panel says which campaign it means.
 *
 * Two changes that were each correct alone produced this between them. The
 * panel became clickable, every step and row carrying a sentence about "this
 * campaign". Separately the panel became a view: a tab click changes what is
 * on screen without moving what the chat is working on, which is the whole
 * point of the note that says so.
 *
 * Together, "this campaign" is written while looking at one campaign and read
 * by an agent holding another. The step click also submitted on its own, so
 * one click on the wrong tab silently edited the other campaign.
 *
 * Both halves are asserted here: the sentence names its campaign, and it is
 * the one being looked at rather than the one in focus.
 */
class PanelClicksNameTheirCampaignTest extends TestCase
{
    use RefreshDatabase;

    public function test_published_linkedin_panel_has_no_publish_blocker_or_device_setting(): void
    {
        [$user, $conversation, $campaign] = $this->twoCampaigns();
        $campaign->update(['platform' => 'linkedin', 'status' => 'published', 'external_campaign_id' => '77']);

        $html = $this->viewing($user, $conversation, $campaign);

        $this->assertStringNotContainsString('Still needed to publish', $html);
        $this->assertStringNotContainsString('already published as', $html);
        $this->assertStringNotContainsString('Devices', $html);
        $this->assertStringContainsString('Published. Delivery status must be checked on the platform.', $html);
    }

    /** The id is a uuid the table does not generate, so it is written directly. */
    private function conversationFor(User $user): Conversation
    {
        $id = (string) Str::uuid();

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

        return Conversation::findOrFail($id);
    }

    /** @return array{0: User, 1: Conversation, 2: Campaign, 3: Campaign} */
    private function twoCampaigns(): array
    {
        $user = User::factory()->create();
        $conversation = $this->conversationFor($user);

        $workspace = app(Workspace::class);
        $workspace->bindTo($conversation->id);
        $workspace->ownedBy($user);

        $meta = Campaign::create([
            'user_id' => $user->id, 'name' => 'Winter Sale Meta', 'platform' => 'meta', 'status' => 'draft',
        ]);
        $google = Campaign::create([
            'user_id' => $user->id, 'name' => 'Winter Sale Google', 'platform' => 'google', 'status' => 'draft',
        ]);

        // Both belong to the conversation; the second one created is in focus,
        // which is what makes looking at the first one the interesting case.
        $workspace->produced($meta);
        $workspace->produced($google);

        return [$user, $conversation, $meta, $google];
    }

    private function viewing(User $user, Conversation $conversation, Campaign $campaign): string
    {
        return (string) $this->actingAs($user)->post(route('chat.view'), [
            'conversation' => $conversation->id,
            'campaign' => (string) $campaign->id,
        ])->assertOk()->json('panelHtml');
    }

    /** The defect: a click that does not say which campaign it is about. */
    public function test_no_click_target_says_this_campaign(): void
    {
        [$user, $conversation, $meta] = $this->twoCampaigns();

        $html = $this->viewing($user, $conversation, $meta);

        $this->assertStringNotContainsString(
            'for this campaign',
            $html,
            'A click sends a sentence the agent resolves against focus, not against the panel on screen.',
        );
    }

    public function test_a_step_click_names_the_campaign_being_looked_at(): void
    {
        [$user, $conversation, $meta, $google] = $this->twoCampaigns();

        $html = $this->viewing($user, $conversation, $meta);

        $this->assertStringContainsString('data-step-prompt', $html, 'The steps should still be clickable.');
        $this->assertStringContainsString('Winter Sale Meta', $html);
        $this->assertStringNotContainsString(
            'data-step-prompt="Help me configure the budget for Winter Sale Google"',
            $html,
            'The panel named the focused campaign rather than the one on screen.',
        );

        unset($google);
    }

    public function test_a_published_linkedin_row_uses_its_own_edit(): void
    {
        [$user, $conversation, $meta, $linkedin] = $this->twoCampaigns();
        $linkedin->update([
            'platform' => 'linkedin',
            'status' => 'published',
            'external_campaign_id' => '77',
            'name' => 'Stock Prices',
            'budget' => 10,
            'budget_mode' => 'daily',
            'currency' => 'USD',
        ]);

        $html = $this->viewing($user, $conversation, $linkedin->fresh());

        $this->assertStringContainsString('Change the ad set name for Stock Prices. Call edit_linkedin_campaign with the new name.', $html);
        $this->assertStringContainsString('Call edit_linkedin_campaign with placements as an empty list so LinkedIn feed and Audience Network can both be picked.', $html);
        $this->assertStringContainsString('call edit_linkedin_campaign with location_query', $html);
        $this->assertStringContainsString('Call edit_linkedin_campaign with audience as an empty list', $html);
        $this->assertStringContainsString('Call edit_linkedin_campaign', $html);
        $this->assertStringContainsString('cannot be changed after it is on LinkedIn', $html);
        $this->assertStringNotContainsString('edit_linkedin_campaign', $this->viewing($user, $conversation, $meta));
    }

    public function test_a_row_click_names_the_campaign_being_looked_at(): void
    {
        [$user, $conversation, $meta] = $this->twoCampaigns();

        $html = $this->viewing($user, $conversation, $meta);

        $this->assertMatchesRegularExpression(
            '/data-row-prompt="I want to update the [^"]+ for Winter Sale Meta\."/',
            $html,
        );
    }

    public function test_completed_ad_copy_step_opens_the_complete_variation_review(): void
    {
        [$user, $conversation, $campaign] = $this->twoCampaigns();
        $campaign->update(['platform' => 'linkedin']);
        $campaign->ads()->create(['headline' => 'Existing headline', 'primary_text' => 'Existing body.', 'cta' => 'LEARN_MORE']);

        $html = $this->viewing($user, $conversation, $campaign);

        $this->assertStringContainsString(
            'data-step-prompt="Show the complete ad-copy variations and the Regenerate ad-copy option for Winter Sale Meta. Do not offer separate headline or body choices."',
            $html,
        );
        $this->assertStringNotContainsString('Review or change the ad copy for', $html);
    }

    public function test_audience_panel_shortcut_carries_a_structured_action_and_campaign(): void
    {
        [$user, $conversation, $campaign] = $this->twoCampaigns();
        $campaign->update(['platform' => 'linkedin', 'ad_account_id' => '556447014']);

        $html = $this->viewing($user, $conversation, $campaign);

        $this->assertStringContainsString('data-panel-action="review_linkedin_audience" data-panel-campaign="'.$campaign->id.'"', $html);
        $this->assertStringNotContainsString('review_audience true', $html);
    }

    /**
     * And the warning is still there, because naming the campaign tells you
     * what a click will do, not what the next thing you type will do.
     */
    public function test_the_working_on_warning_still_appears(): void
    {
        [$user, $conversation, $meta] = $this->twoCampaigns();

        $this->assertStringContainsString(
            'Winter Sale Google',
            $this->viewing($user, $conversation, $meta),
            'Looking at one campaign while the chat works on another should still say so.',
        );
    }

    /**
     * A live campaign is not shown as partway through the launch.
     *
     * The progress bar describes building a campaign up to its first publish.
     * On a published one it kept counting toward a launch that had already
     * happened and naming the next unfinished step, so a campaign that had been
     * on Meta for days read "9 of 10, next: creatives".
     */
    public function test_a_published_campaign_is_not_shown_as_mid_launch(): void
    {
        [$user, $conversation, $meta] = $this->twoCampaigns();

        $meta->update([
            'status' => 'published',
            'external_campaign_id' => '120111',
        ]);

        $html = $this->viewing($user, $conversation, $meta->fresh());

        $this->assertStringContainsString('On Meta', $html);
        $this->assertStringNotContainsString('Next:', $html);
    }

    /** A draft still shows what it is waiting for. */
    public function test_a_draft_still_shows_its_next_step(): void
    {
        [$user, $conversation, $meta] = $this->twoCampaigns();

        $this->assertStringContainsString('Next:', $this->viewing($user, $conversation, $meta));
    }

    /**
     * An ad set added to the campaign is visible.
     *
     * The rows describe the first ad set, because the campaign's own attributes
     * address it. So a second one was invisible here: a buyer asked for another
     * audience, it was created on Meta, and the panel carried on showing one
     * set of countries and one budget.
     */
    public function test_an_added_ad_set_appears_in_the_panel(): void
    {
        [$user, $conversation, $meta] = $this->twoCampaigns();

        $meta->adSets()->create([
            'position' => 2,
            'name' => 'UK test',
            'locations' => ['countries' => ['GB']],
            'budget' => 15,
            'budget_mode' => 'daily',
            'external_adset_id' => 'adset-2',
            'status' => 'published',
        ]);

        $html = $this->viewing($user, $conversation, $meta);

        $this->assertStringContainsString('Other ad sets', $html);
        $this->assertStringContainsString('UK test', $html);
        $this->assertStringContainsString('GB', $html);
        $this->assertStringContainsString('15.00', $html);

        // Whether it is on the platform is the difference between an ad set that
        // can spend and one that is only written here.
        $this->assertStringContainsString('paused', $html);
    }

    /** An ad set written but not sent says so rather than looking live. */
    public function test_an_unsent_ad_set_is_marked_as_not_sent(): void
    {
        [$user, $conversation, $meta] = $this->twoCampaigns();

        $meta->adSets()->create([
            'position' => 2,
            'name' => 'Draft audience',
            'locations' => ['countries' => ['GB']],
        ]);

        $this->assertStringContainsString(
            'not sent yet',
            $this->viewing($user, $conversation, $meta),
        );
    }

    /** The ordinary one-ad-set campaign is unchanged. */
    public function test_a_single_ad_set_campaign_shows_no_extra_section(): void
    {
        [$user, $conversation, $meta] = $this->twoCampaigns();

        $this->assertStringNotContainsString('Other ad sets', $this->viewing($user, $conversation, $meta));
    }
}
