<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('support_conversations', function (Blueprint $table) {
            $table->id();
            $table->string('conversation_id')->unique(); // Public-facing ID
            $table->foreignId('brand_id')->constrained()->onDelete('cascade');
            $table->foreignId('customer_id')->nullable()->constrained('users')->onDelete('set null');
            $table->string('customer_name')->nullable();
            $table->string('customer_email')->nullable();
            $table->string('customer_phone')->nullable();
            $table->enum('channel', ['widget', 'email', 'api', 'chat'])->default('widget');
            $table->enum('status', ['active', 'resolved', 'escalated', 'closed'])->default('active');
            $table->text('initial_query')->nullable();
            $table->json('metadata')->nullable(); // session info, device, location, etc.
            $table->boolean('escalated_to_human')->default(false);
            $table->foreignId('assigned_agent_id')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamp('escalated_at')->nullable();
            $table->timestamp('resolved_at')->nullable();
            $table->timestamp('closed_at')->nullable();
            $table->integer('total_messages')->default(0);
            $table->decimal('avg_confidence_score', 5, 2)->nullable();
            $table->integer('satisfaction_rating')->nullable(); // 1-5 stars
            $table->text('satisfaction_feedback')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index(['brand_id', 'status']);
            $table->index(['brand_id', 'created_at']);
            $table->index(['customer_email', 'brand_id']);
            $table->index('conversation_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('support_conversations');
    }
};