<?php

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

/**
 * medacc_journal_entries — GL journal entry headers (SIFA §25 journal_entry).
 *
 * A balanced (total_debit == total_credit) double-entry document. `reference_type`
 * / `reference_id` link a journal entry back to the ERP event it was derived from
 * (invoice/payment/payroll/purchase/expense) or `manual` for hand entries — this
 * pair is the idempotency key AutoPostingService uses to never double-post.
 *
 * status: draft → posted → reversed. A posted entry is immutable; corrections are
 * made by posting a mirror reversing entry (LedgerService::reverse).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medacc_journal_entries')) {
            return;
        }

        Schema::create('medacc_journal_entries', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->string('entry_no', 40); // JE-{biz}-{seq}
            $t->date('date');
            $t->text('description')->nullable();
            $t->enum('reference_type', ['invoice', 'payment', 'payroll', 'purchase', 'expense', 'manual'])->nullable();
            $t->unsignedBigInteger('reference_id')->nullable();
            $t->enum('status', ['draft', 'posted', 'reversed'])->default('draft');
            $t->unsignedInteger('posted_by')->nullable();  // users.id
            $t->dateTime('posted_at')->nullable();
            $t->unsignedInteger('reversed_by')->nullable(); // users.id
            $t->dateTime('reversed_at')->nullable();
            $t->unsignedBigInteger('reversal_of_id')->nullable(); // this entry reverses that entry
            $t->decimal('total_debit', 22, 4)->default(0);
            $t->decimal('total_credit', 22, 4)->default(0);
            $t->unsignedInteger('created_by')->nullable(); // users.id
            $t->timestamps();

            $t->unique(['business_id', 'entry_no'], 'medacc_je_biz_entryno_uq');
            $t->index(['business_id', 'status'], 'medacc_je_biz_status_idx');
            $t->index(['business_id', 'date'], 'medacc_je_biz_date_idx');
            $t->index(['business_id', 'reference_type', 'reference_id'], 'medacc_je_ref_idx');
        });
    }

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