<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Config-driven PAYE. A tax_table is a versioned ruleset (selected by code +
 * effective date, mirroring the salary tables) carrying the Consolidated Relief
 * Allowance parameters and the statutory minimum-tax rate; tax_bands hold its
 * graduated rate steps. This replaces the hardcoded constants in
 * PitaPayeStrategy so the bands and reliefs can be maintained from the UI.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('tax_tables', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('code')->default('PITA'); // matches payroll_runs.statutory_ruleset
            $table->date('effective_from');
            $table->date('effective_to')->nullable();

            // Consolidated Relief Allowance = max(cra_fixed_min, cra_alt_percent
            // * gross) + cra_gross_percent * gross.
            $table->decimal('cra_fixed_min', 14, 2)->default(200000);
            $table->decimal('cra_alt_percent', 6, 4)->default(0.01);
            $table->decimal('cra_gross_percent', 6, 4)->default(0.20);

            // Statutory minimum tax as a fraction of gross income (0 = none).
            $table->decimal('min_tax_percent', 6, 4)->default(0);

            $table->boolean('active')->default(true);
            $table->timestamps();

            $table->index(['code', 'effective_from']);
        });

        Schema::create('tax_bands', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tax_table_id')->constrained()->cascadeOnDelete();
            $table->unsignedInteger('sort')->default(0);
            // Band width (slice of taxable income). NULL = open-ended top band.
            $table->decimal('width', 14, 2)->nullable();
            $table->decimal('rate', 6, 4);
            $table->timestamps();

            $table->index(['tax_table_id', 'sort']);
        });
    }

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