<?php

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

/**
 * medacc_accounts — the chart of accounts (SIFA §25 chart_of_accounts).
 *
 * A hierarchical, business-scoped COA layered ON TOP of the ERP's existing
 * payment-level double-entry (app/Account + app/AccountTransaction). This is the
 * GL account master the journal layer posts to; it does NOT replace the ERP's
 * `accounts` table (which stays the cash/bank register the POS pays into).
 *
 * `code` is a hierarchical string (e.g. 1000 / 1100 / 1110) unique per business.
 * `is_system` marks the seeded standard medical defaults (idempotent, never
 * user-deleted). `parent_id` self-references for the account tree.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medacc_accounts')) {
            return;
        }

        Schema::create('medacc_accounts', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->string('code', 40);
            $t->string('name', 191);
            $t->enum('type', ['asset', 'liability', 'equity', 'revenue', 'expense']);
            $t->string('sub_type', 60)->nullable(); // current_asset, fixed_asset, current_liability, …
            $t->unsignedBigInteger('parent_id')->nullable(); // self FK (medacc_accounts.id)
            $t->boolean('is_active')->default(true);
            $t->boolean('is_system')->default(false); // seeded defaults
            $t->text('description')->nullable();
            $t->timestamps();

            $t->unique(['business_id', 'code'], 'medacc_accounts_biz_code_uq');
            $t->index(['business_id', 'type'], 'medacc_accounts_biz_type_idx');
            $t->index('parent_id', 'medacc_accounts_parent_idx');

            $t->foreign('parent_id')
                ->references('id')->on('medacc_accounts')
                ->onDelete('set null');
        });
    }

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