<?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('tickets', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('brand_id')->nullable();
            $table->unsignedInteger('client_id')->nullable();
            $table->unsignedBigInteger('client_product_id')->nullable();
            $table->unsignedBigInteger('client_domain_id')->nullable();
            $table->unsignedInteger('contact_id')->nullable();
            $table->string('mail');
            $table->unsignedInteger('department_id');
            $table->unsignedBigInteger('status_id')->nullable();
            $table->unsignedBigInteger('sla_plan_id')->nullable();
            $table->string('title');
            $table->uuid('uuid')->unique();
            $table->string('secure_hash')->nullable();
            $table->enum('priority', ['low', 'medium', 'high', 'urgent'])->default('medium')->nullable(false);
            $table->boolean('is_flagged')->default(false);
            $table->unsignedBigInteger('flagged_by')->nullable();
            $table->string('cc_emails', 1000)->nullable();
            $table->string('source', 20)->default('web');
            $table->string('slack_channel_id')->nullable();
            $table->string('slack_thread_ts')->nullable();
            $table->string('telegram_message_id')->nullable();
            $table->string('discord_message_id', 50)->nullable();
            $table->string('discord_thread_id', 50)->nullable();
            $table->timestamp('first_response_due_at')->nullable();
            $table->timestamp('first_response_at')->nullable();
            $table->timestamp('resolution_due_at')->nullable();
            $table->timestamp('resolved_at')->nullable();
            $table->timestamp('rating_reminder_sent_at')->nullable();
            $table->boolean('sla_first_response_breached')->default(false);
            $table->boolean('sla_resolution_breached')->default(false);
            $table->timestamp('last_client_reply_at')->nullable();
            $table->timestamp('last_admin_reply_at')->nullable();
            $table->timestamps();

            $table->foreign('status_id')->references('id')->on('ticket_statuses')->onDelete('set null');
            $table->foreign('client_product_id')->references('id')->on('client_products')->onDelete('set null');
            $table->foreign('client_domain_id')->references('id')->on('client_domains')->onDelete('set null');

            $table->index('client_id');
            $table->index('department_id');
            $table->index('priority');
            $table->index('brand_id');
            $table->index('status_id');
        });
    }

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