<?php

namespace Tests\Feature;

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

/**
 * The buyer never typed the system aside, so it is not shown as theirs.
 *
 * When a turn stops for an approval and the user sends another message instead,
 * ChatController prepends a note to the message the model receives, telling it
 * to say the approval did not happen. Its own docblock calls it "a system aside
 * rather than the user's words" - and it is stored on the user's row, because
 * that row is what the turn was given.
 *
 * So the transcript showed it as something the buyer had written:
 *
 *   [System: the previous turn stopped and waited for the user to approve
 *   campaign add ad set, and they did not - they sent this message instead.
 *   Nothing was sent to the platform and nothing changed...]
 *
 * Seen on the dev server on 5 Oct, three in a row in one chat while testing
 * add_ad_set. It reads as the product talking to itself in the buyer's voice,
 * and quotes instructions they never gave.
 */
class ASystemAsideIsNotShownAsTheUsersWordsTest extends TestCase
{
    use RefreshDatabase;

    private const ASIDE = '[System: the previous turn stopped and waited for the user to approve '
        .'campaign add ad set, and they did not - they sent this message instead. Nothing was sent '
        .'to the platform and nothing changed.]';

    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' => 'Approval stranded',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return Conversation::findOrFail($id);
    }

    private function say(Conversation $conversation, User $user, string $role, string $content): void
    {
        DB::table('agent_conversation_messages')->insert([
            'id' => (string) Str::uuid(),
            'conversation_id' => $conversation->id,
            'participant_type' => $user->getMorphClass(),
            'participant_id' => $user->getKey(),
            // Not nullable, and none of them what this is about.
            'agent' => 'marketing',
            'attachments' => '[]',
            'tool_calls' => '[]',
            'tool_results' => '[]',
            'usage' => '[]',
            'meta' => '[]',
            'role' => $role,
            'content' => $content,
            // Ordered, because the transcript sorts on this and two rows
            // written in the same test share a timestamp otherwise.
            'created_at' => now()->addMicroseconds(
                DB::table('agent_conversation_messages')->count() + 1,
            ),
            'updated_at' => now(),
        ]);
    }

    private function page(User $user, Conversation $conversation): TestResponse
    {
        return $this->actingAs($user)
            ->get(route('chat.show', ['conversation' => $conversation->id]))
            ->assertOk();
    }

    public function test_the_aside_is_not_shown_and_the_message_is(): void
    {
        $user = User::factory()->create();
        $conversation = $this->conversationFor($user);

        $this->say($conversation, $user, 'user', self::ASIDE."\n\nAdd another ad set for the UK.");

        $this->page($user, $conversation)
            ->assertSee('Add another ad set for the UK.', escape: false)
            ->assertDontSee('[System:', escape: false);
    }

    /**
     * A turn that was nothing but the aside shows nothing at all.
     *
     * The buyer said nothing on it, so an empty bubble attributed to them is
     * worse than no bubble.
     */
    public function test_a_turn_that_was_only_an_aside_is_dropped(): void
    {
        $user = User::factory()->create();
        $conversation = $this->conversationFor($user);

        $this->say($conversation, $user, 'user', self::ASIDE);
        $this->say($conversation, $user, 'assistant', 'That did not happen. Shall I try again?');

        $this->page($user, $conversation)
            ->assertSee('That did not happen. Shall I try again?', escape: false)
            ->assertDontSee('[System:', escape: false);
    }

    /** An ordinary message is untouched. */
    public function test_an_ordinary_message_is_unchanged(): void
    {
        $user = User::factory()->create();
        $conversation = $this->conversationFor($user);

        $this->say($conversation, $user, 'user', 'Add another ad set for the UK.');

        $this->page($user, $conversation)->assertSee('Add another ad set for the UK.', escape: false);
    }

    /**
     * Only at the start, which is the only place one is ever put.
     *
     * Someone writing about a bracketed line mid-message keeps every word of it,
     * rather than having their own text silently cut.
     */
    public function test_bracketed_text_later_in_a_message_is_kept(): void
    {
        $user = User::factory()->create();
        $conversation = $this->conversationFor($user);

        $said = 'The log said [System: something failed] and I want to know why.';
        $this->say($conversation, $user, 'user', $said);

        $this->page($user, $conversation)->assertSee($said, escape: false);
    }
}
