<?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
    {
        if (Schema::hasTable('tickets')) {
            return;
        }

        Schema::create('tickets', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->constrained()->onDelete('cascade');
            $table->foreignId('customer_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('last_replied_by')->nullable()->constrained('users')->nullOnDelete();
            $table->string('subject', 191);
            $table->string('category', 50)->default('order_issue');
            $table->string('priority', 20)->default('medium');
            $table->string('status', 20)->default('open');
            $table->string('active_ticket_key', 191)->nullable();
            $table->timestamp('last_reply_at')->nullable();
            $table->timestamp('closed_at')->nullable();
            $table->timestamps();

            $table->index(['customer_id', 'status']);
            $table->index(['order_id', 'status']);
            $table->index('last_reply_at');
            $table->unique('active_ticket_key');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('tickets');
    }
};
