<?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('reply_suggestions', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('contact_id')->constrained('contacts')->cascadeOnDelete();
            $table->foreignUuid('conversation_id')->constrained('conversations')->cascadeOnDelete();
            $table->foreignId('created_by')->constrained('users')->cascadeOnDelete();
            $table->text('suggested_body');
            $table->string('generated_by', 16);
            $table->string('status', 16)->default('pending');
            $table->text('sent_body')->nullable();
            $table->unsignedInteger('estimated_time_saved_seconds')->default(0);
            $table->timestamp('resolved_at')->nullable();
            $table->timestamps();

            $table->index(['tenant_id', 'conversation_id', 'status']);
            $table->index(['tenant_id', 'created_by', 'status']);
        });

        Schema::create('ai_copilot_metrics', function (Blueprint $table): void {
            $table->uuid('id')->primary();
            $table->foreignUuid('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignUuid('contact_id')->nullable()->constrained('contacts')->nullOnDelete();
            $table->foreignUuid('conversation_id')->nullable()->constrained('conversations')->nullOnDelete();
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignUuid('reply_suggestion_id')->nullable()->constrained('reply_suggestions')->nullOnDelete();
            $table->string('event_type', 48);
            $table->string('generated_by', 16)->nullable();
            $table->unsignedInteger('estimated_time_saved_seconds')->default(0);
            $table->jsonb('metadata')->nullable();
            $table->timestamps();

            $table->index(['tenant_id', 'event_type', 'created_at']);
            $table->index(['tenant_id', 'created_at']);
        });
    }

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