<?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('employee_access_details', function (Blueprint $table) {
            $table->id();
            $table->foreignId('employee_id')->constrained('employees')->onDelete('cascade');
            $table->foreignId('access_catalog_id')->constrained('access_catalogs');
            $table->date('granted_date');
            $table->date('original_expiry_date'); // Tanggal pensiun/resign asli
            $table->date('current_expiry_date');  // Bisa berubah jika extended
            $table->enum('status', ['active', 'extended', 'revoked', 'scheduled_revoke', 'pending_revoke'])->default('active');
            $table->boolean('is_extended')->default(false);
            $table->integer('extension_count')->default(0);
            $table->timestamp('last_extended_at')->nullable();
            $table->foreignId('last_extended_by')->nullable()->constrained('users')->nullOnDelete();
            $table->date('revocation_date')->nullable();
            $table->foreignId('revoked_by')->nullable()->constrained('users')->nullOnDelete();
            $table->text('revocation_notes')->nullable();
            $table->timestamps();
            
            // Indexing penting untuk scheduler
            $table->index(['current_expiry_date', 'status']);
            $table->index(['employee_id', 'status']);
            $table->index(['access_catalog_id', 'status']);
            $table->unique(['employee_id', 'access_catalog_id']); // 1 pegawai 1 akses unik
        });
    }

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