<?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 Tests\TestCase;

/**
 * A new chat is empty, and the server is what decides that.
 *
 * ChatController::resolveConversation() has returned null for ?new=1 since 8 Sep.
 * Prod served the previous conversation anyway: on 30 Sep, and still on 6 Oct,
 * /chat?new=1 came back with that chat's id, its whole transcript, its campaign
 * and the publish approval it was parked on. Both times it was read as a stale
 * build. It was neither. The vhost's PHP fallback was
 *
 *   try_files $uri $uri/ /index.php;
 *
 * with the ?$query_string missing, so no GET parameter reached the application
 * and ?new=1 never arrived. Confirmed by /chat?conversation=not-a-real-id
 * answering 200 with the most recent conversation instead of 404, which can only
 * happen when the parameter is an empty string.
 *
 * On 30 Sep the response was a guard in chat.js that emptied the transcript in the
 * browser. That hid the fault rather than fixing it: the symptom stopped being
 * "my new chat is showing somebody else's twenty messages", which names its own
 * cause, and became a lone "Approve publishing?" over a campaign the user had
 * never made. The guard was removed on 6 Oct and this took its place, because the
 * thing worth testing is what the server sends, and that was never broken.
 *
 * tests/js/new-chat.cjs still covers the half that is genuinely the browser's: a
 * first message must not invent a conversation id, and the starter cards survive.
 * It is run from FourThingsTheBrowserWasDoingTest, so it is not run again here.
 */
class ANewChatDoesNotInheritTheLastOneTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    private string $conversationId;

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

        $this->user = User::factory()->create();
        $this->conversationId = (string) Str::uuid();

        DB::table('agent_conversations')->insert([
            'id' => $this->conversationId,
            'participant_type' => $this->user->getMorphClass(),
            'participant_id' => $this->user->getKey(),
            'title' => 'Winter Sale on Meta',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->say('user', 'Advertise allbirds.com on Meta');
        $this->say('assistant', 'Here is what I have so far.');

        // A local instance, not app(Workspace::class), which is a scoped binding
        // and would still be bound to this conversation when the request below
        // runs. Over HTTP the container is fresh and only bindWorkspace() binds
        // it, which is the behaviour being asserted; binding it here would make
        // ?new=1 look like it had inherited a campaign when nothing had.
        $workspace = new Workspace($this->conversationId);
        $workspace->ownedBy($this->user);

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

        $workspace->produced($campaign);
        $workspace->focusOn($campaign);

        // The question the chat was parked on, which is what turned up in a brand
        // new chat on prod.
        $workspace->rememberChoices([[
            'field' => 'publish_approval',
            'question' => 'Approve publishing? It will be created paused.',
            'options' => [['label' => 'Approve & Publish', 'value' => 'approve']],
            'multiple' => false,
            'allow_other' => false,
        ]]);
    }

    private function say(string $role, string $content): void
    {
        DB::table('agent_conversation_messages')->insert([
            'id' => (string) Str::uuid(),
            'conversation_id' => $this->conversationId,
            'participant_type' => $this->user->getMorphClass(),
            'participant_id' => $this->user->getKey(),
            'agent' => 'marketing',
            'attachments' => '[]',
            'tool_calls' => '[]',
            'tool_results' => '[]',
            'usage' => '[]',
            'meta' => '[]',
            'role' => $role,
            'content' => $content,
            'created_at' => now()->addMicroseconds(
                DB::table('agent_conversation_messages')->count() + 1,
            ),
            'updated_at' => now(),
        ]);
    }

    private function page(string $url): string
    {
        return $this->actingAs($this->user)->get($url)->assertOk()->getContent();
    }

    /** What the JS config block was given, which is what the page renders from. */
    private function config(string $html, string $key): string
    {
        preg_match('/'.preg_quote($key, '/').': (.*?),\n/s', $html, $matches);

        return trim($matches[1] ?? '<absent>');
    }

    /**
     * The campaign drawer's contents on their own.
     *
     * Asserted against rather than the whole page, because the sidebar lists the
     * user's recent chats by title on every page including this one, which is
     * correct: a new chat should still show you your other chats.
     */
    private function panel(string $html): string
    {
        preg_match('/id="panel">(.*?)<\/div>/s', $html, $matches);

        return trim($matches[1] ?? '<absent>');
    }

    /** Everything the previous chat had, none of which belongs to a new one. */
    public function test_a_new_chat_inherits_nothing(): void
    {
        $html = $this->page('/chat?new=1');

        $this->assertSame('null', $this->config($html, 'conversation'));
        $this->assertSame('[]', $this->config($html, 'choices'));
        $this->assertSame('false', $this->config($html, 'hasCampaign'));
        $this->assertStringNotContainsString('Advertise allbirds.com on Meta', $html);
        // The one that reached a user: a brand new chat offering to publish a
        // campaign they had never made.
        $this->assertStringNotContainsString('Approve publishing?', $html);
        $this->assertStringContainsString('No campaign yet', $this->panel($html));
    }

    /**
     * An id that does not resolve is refused rather than quietly swapped.
     *
     * This is the assertion that identified the real fault. Prod answered 200 with
     * the most recent conversation, which only happens when the parameter arrived
     * empty, because a bad id reaches readableConversation() and 404s.
     */
    public function test_an_unknown_conversation_is_a_not_found(): void
    {
        $this->actingAs($this->user)->get('/chat?conversation=not-a-real-id')->assertNotFound();
    }
}
