<?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('attendance_exceptions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('employee_id')->constrained('employees')->cascadeOnDelete();
            $table->foreignId('attendance_record_id')->nullable()->constrained('attendance_records')->nullOnDelete();
            $table->string('type', 48);
            $table->string('severity', 16);
            $table->string('status', 16)->default('pending');
            $table->timestamp('detected_at');
            $table->foreignId('resolved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('resolved_at')->nullable();
            $table->text('resolution_note')->nullable();
            $table->json('metadata')->nullable();
            $table->string('dedupe_key', 64);
            $table->timestamps();

            $table->unique(['tenant_id', 'dedupe_key']);
            $table->index(['tenant_id', 'status', 'severity', 'detected_at'], 'att_ex_tenant_status_sev_det_idx');
            $table->index(['tenant_id', 'employee_id', 'detected_at'], 'att_ex_tenant_emp_det_idx');
            $table->index(['tenant_id', 'type', 'status'], 'att_ex_tenant_type_status_idx');
        });
    }

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