<?php

use App\Domain\Document\Enums\DocumentStatus;
use App\Domain\Document\Enums\DocumentType;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('documents', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->string('documentable_type', 100);
            $table->unsignedBigInteger('documentable_id');
            $table->string('document_type', 30);
            $table->string('file_path', 500);
            $table->string('original_filename', 255);
            $table->string('mime_type', 100);
            $table->bigInteger('file_size');
            $table->string('status', 20)->default('pending');
            $table->date('expires_at')->nullable();
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->dateTime('approved_at')->nullable();
            $table->text('rejection_reason')->nullable();
            $table->text('notes')->nullable();
            $table->foreignId('uploaded_by')->constrained('users');
            $table->foreignId('created_by')->constrained('users');
            $table->timestamps();
            $table->softDeletes();

            $table->index(['academy_id', 'documentable_type', 'documentable_id'], 'documents_polymorphic_idx');
            $table->index(['academy_id', 'status']);
            $table->index(['academy_id', 'document_type', 'status']);
            $table->index('expires_at');
        });

        $types = implode("','", array_column(DocumentType::cases(), 'value'));
        DB::statement("ALTER TABLE documents ADD CONSTRAINT documents_document_type_check CHECK (document_type IN ('{$types}'))");

        $statuses = implode("','", array_column(DocumentStatus::cases(), 'value'));
        DB::statement("ALTER TABLE documents ADD CONSTRAINT documents_status_check CHECK (status IN ('{$statuses}'))");
    }

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