<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up(): void
    {
        Schema::create('homepage_leads', function (Blueprint $table) {
            $table->id();
            $table->uuid('session_id')->unique();

            // Visitor info from the intro form
            $table->string('name');
            $table->string('email')->nullable();
            $table->string('company')->nullable();
            $table->string('use_case', 40)->nullable();
            $table->string('page_url', 500)->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->string('user_agent', 500)->nullable();

            // Full chat transcript: [{ role: 'user'|'agent', content: '...', at: ISO8601 }]
            $table->json('transcript')->nullable();

            // Lifecycle
            $table->enum('status', ['new', 'contacted', 'qualified', 'closed', 'spam'])->default('new');
            $table->text('admin_notes')->nullable();

            // AI accounting — total across the whole conversation
            $table->string('ai_provider', 30)->nullable();
            $table->string('ai_model', 60)->nullable();
            $table->unsignedInteger('ai_tokens_in')->default(0);
            $table->unsignedInteger('ai_tokens_out')->default(0);
            $table->decimal('ai_total_cost', 10, 6)->default(0);
            $table->unsignedSmallInteger('message_count')->default(0);

            $table->timestamp('last_message_at')->nullable();
            $table->timestamps();

            $table->index('status');
            $table->index('email');
            $table->index('created_at');
            $table->index('last_message_at');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('homepage_leads');
    }
};
