<?php

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

/**
 * medacc_periods — accounting periods (SIFA §25 period_management).
 *
 * A period is open or closed. LedgerService refuses to post a journal entry whose
 * date falls inside a CLOSED period (the period lock that prevents backdated
 * posting). When no period row covers an entry's date, posting is allowed (the
 * period lock is opt-in — a business that never defines periods is never blocked).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medacc_periods')) {
            return;
        }

        Schema::create('medacc_periods', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->string('name', 60); // e.g. '2026-07'
            $t->date('start_date');
            $t->date('end_date');
            $t->enum('status', ['open', 'closed'])->default('open');
            $t->unsignedInteger('closed_by')->nullable(); // users.id
            $t->dateTime('closed_at')->nullable();
            $t->timestamps();

            $t->unique(['business_id', 'name'], 'medacc_periods_biz_name_uq');
            $t->index(['business_id', 'start_date', 'end_date'], 'medacc_periods_biz_range_idx');
            $t->index(['business_id', 'status'], 'medacc_periods_biz_status_idx');
        });
    }

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