<?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
    {
        if (Schema::hasTable('complaints')) {
            return;
        }

        Schema::create('complaints', function (Blueprint $table) {
            $table->id();
            $table->string('ticket_number')->unique();
            $table->enum('source', ['phone', 'mobile_app', 'panic_button', 'whatsapp', 'sms'])->default('phone');
            $table->string('caller_phone')->nullable();
            $table->string('caller_name')->nullable();
            $table->text('description');
            $table->enum('category', ['emergency_police', 'emergency_medical', 'emergency_fire', 'emergency_disaster', 'non_emergency'])->default('emergency_police');
            $table->enum('status', ['pending', 'processing', 'dispatched', 'in_progress', 'completed', 'cancelled'])->default('pending');
            $table->enum('priority', ['low', 'medium', 'high', 'critical'])->default('medium');
            // Use unsignedBigInteger instead of foreignId to avoid auto-constraint
            // Constraint will be added in a separate migration after locations table is created
            $table->unsignedBigInteger('location_id')->nullable();
            $table->foreignId('polda_id')->nullable()->constrained('poldas')->onDelete('set null');
            $table->foreignId('polres_id')->nullable()->constrained('polres')->onDelete('set null');
            $table->foreignId('polsek_id')->nullable()->constrained('polsek')->onDelete('set null');
            $table->foreignId('operator_id')->nullable()->constrained('users')->onDelete('set null');
            $table->text('ai_classification')->nullable();
            $table->json('keywords')->nullable();
            $table->timestamp('received_at');
            $table->timestamp('dispatched_at')->nullable();
            $table->timestamp('resolved_at')->nullable();
            $table->timestamps();
        });
    }

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