<?php

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

/**
 * medacc_journal_lines — the debit/credit legs of a journal entry
 * (SIFA §25 journal_entry.lines).
 *
 * Each line hits one COA account (account_id → medacc_accounts) with EITHER a
 * debit OR a credit amount (the other is 0). Optional cost_center_id allocates the
 * line to a department / facility / project for departmental P&L.
 *
 * business_id is denormalised onto the line so every GL report query stays
 * business-scoped without joining the header.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medacc_journal_lines')) {
            return;
        }

        Schema::create('medacc_journal_lines', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedBigInteger('journal_entry_id');
            $t->unsignedBigInteger('account_id'); // medacc_accounts.id
            $t->decimal('debit', 22, 4)->default(0);
            $t->decimal('credit', 22, 4)->default(0);
            $t->string('description', 255)->nullable();
            $t->unsignedBigInteger('cost_center_id')->nullable(); // medacc_cost_centers.id
            $t->timestamps();

            $t->index(['business_id', 'account_id'], 'medacc_jl_biz_account_idx');
            $t->index('journal_entry_id', 'medacc_jl_entry_idx');
            $t->index('cost_center_id', 'medacc_jl_cc_idx');

            $t->foreign('journal_entry_id')
                ->references('id')->on('medacc_journal_entries')
                ->onDelete('cascade');
        });
    }

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