<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Modules\Accounts\Enums\AccountingPeriodStatusEnum;
use Modules\Accounts\Enums\PeriodTypeEnum;
use Modules\Core\Enums\OpenCloseEnum;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('accounting_periods', function (Blueprint $table) {
            $table->id();
            $table->foreignId('fiscal_year_id')->constrained('fiscal_years')->cascadeOnDelete();
            $table->string('name')->comment('e.g. Jul 2025');
            $table->unsignedTinyInteger('period_no')->comment('1-12');
            $table->enum('period_type', PeriodTypeEnum::casesAsArray())->default(PeriodTypeEnum::MONTHLY->value);
            $table->date('start_date');
            $table->date('end_date');
            $table->boolean('is_current')->default(false)->index();
            $table->enum('status', AccountingPeriodStatusEnum::casesAsArray())->index()->default(AccountingPeriodStatusEnum::OPEN->value);
            $table->date('lock_date')->nullable();
            $table->timestamp('locked_at')->nullable();
            $table->timestamp('closed_at')->nullable();
            $table->foreignId('opened_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('closed_by')->nullable()->constrained('users')->nullOnDelete();
            $table->text('note')->nullable();
            $table->timestamps();

            $table->unique(
                ['fiscal_year_id', 'period_no'],
                'uniq_fiscal_period_no'
            );
            $table->index(['start_date', 'end_date']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('accounting_periods');
    }
};
