<?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
    {
        // 1) Tambah generated column: NULL kalau void, 1 kalau aktif
        Schema::table('invoices', function (Blueprint $table) {
            $table->unsignedTinyInteger('active_key')
                ->nullable()
                ->storedAs("IF(status = 'void', NULL, 1)")
                ->after('status');
        });

        // 2) Drop unique lama
        Schema::table('invoices', function (Blueprint $table) {
            $table->dropUnique('uniq_invoice_period');
        });

        // 3) Buat unique baru yang “aktif saja”
        Schema::table('invoices', function (Blueprint $table) {
            $table->unique(
                ['tenant_id', 'period_type', 'period_start', 'period_end', 'active_key'],
                'uniq_invoice_period_active'
            );
        });

        // Opsional: index untuk lookup generator (biar cepat)
        Schema::table('invoices', function (Blueprint $table) {
            $table->index(['tenant_id', 'period_type', 'period_start', 'period_end', 'status'], 'idx_invoice_lookup');
        });
    }

    public function down(): void
    {
        Schema::table('invoices', function (Blueprint $table) {
            $table->dropIndex('idx_invoice_lookup');
            $table->dropUnique('uniq_invoice_period_active');
        });

        Schema::table('invoices', function (Blueprint $table) {
            $table->unique(['tenant_id', 'period_type', 'period_start', 'period_end'], 'uniq_invoice_period');
            $table->dropColumn('active_key');
        });
    }
};
