<?php

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('assignments', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('user_id')->constrained('users');
            $table->nullableMorphs('assignable');
            $table->string('role_label', 100)->nullable();
            $table->string('scope', 30)->default('full');
            $table->string('status', 30)->default('active');
            $table->date('start_date');
            $table->date('end_date')->nullable();
            $table->time('start_time')->nullable();
            $table->time('end_time')->nullable();
            $table->boolean('is_primary')->default(false);
            $table->text('notes')->nullable();
            $table->jsonb('schedule_days')->default('[]');
            $table->jsonb('metadata')->default('{}');
            $table->foreignId('created_by')->constrained('users');
            $table->timestamps();
            $table->softDeletes();

            $table->index(['academy_id', 'user_id', 'status']);
            $table->index(['assignable_type', 'assignable_id', 'status']);
            $table->index(['user_id', 'start_date', 'end_date']);
        });

        DB::statement("ALTER TABLE assignments ADD CONSTRAINT assignments_scope_check CHECK (scope IN ('full', 'partial', 'supervising', 'assisting', 'observing'))");
        DB::statement("ALTER TABLE assignments ADD CONSTRAINT assignments_status_check CHECK (status IN ('active', 'suspended', 'completed', 'cancelled'))");
    }

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