<?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('component_enrolments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('employee_id')->constrained('employees')->cascadeOnDelete();
            $table->foreignId('pay_component_id')->constrained('pay_components')->cascadeOnDelete();

            // Per-employee overrides. amount used for FIXED components (e.g. this
            // person's specific coop deduction); rate for PERCENT_OF overrides.
            $table->decimal('amount', 15, 2)->nullable();
            $table->decimal('rate', 9, 4)->nullable();

            $table->boolean('active')->default(true);
            $table->date('effective_from');
            $table->date('effective_to')->nullable();

            $table->timestamps();

            $table->unique(['employee_id', 'pay_component_id', 'effective_from'], 'enrolment_unique');
            $table->index(['pay_component_id', 'active']);
        });
    }

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