<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\AiConversation;
use App\Models\AiMessage;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdminAiChatControllerTest extends TestCase
{
    use RefreshDatabase;

    private User $admin;

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

        $this->admin = User::factory()->create([
            'is_admin' => true,
            'admin_approved_at' => now(),
        ]);

        $this->actingAs($this->admin);
    }

    public function test_admin_can_view_conversations_list(): void
    {
        AiConversation::factory()
            ->for($this->admin)
            ->has(AiMessage::factory()->count(3), 'messages')
            ->create();

        $response = $this->get(route('admin.ai-chat.index'));

        $response->assertStatus(200);
        $response->assertSee('Conversations');
        $response->assertSee('Total Conversations');
    }

    public function test_admin_can_create_conversation(): void
    {
        $response = $this->post(route('admin.ai-chat.create'));

        $response->assertRedirect();

        $this->assertDatabaseHas('ai_conversations', [
            'user_id' => $this->admin->id,
        ]);
    }

    public function test_admin_can_view_conversation(): void
    {
        $conversation = AiConversation::factory()
            ->for($this->admin)
            ->has(AiMessage::factory()->count(2), 'messages')
            ->create();

        $response = $this->get(route('admin.ai-chat.show', $conversation->ulid));

        $response->assertStatus(200);
        $response->assertSee('Conversation Details');
    }

    public function test_admin_can_delete_conversation(): void
    {
        $conversation = AiConversation::factory()
            ->for($this->admin)
            ->create();

        $response = $this->delete(route('admin.ai-chat.delete', $conversation->ulid));

        $response->assertRedirect(route('admin.ai-chat.index'));

        $this->assertDatabaseMissing('ai_conversations', [
            'id' => $conversation->id,
        ]);
    }
}
