<?php

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

/**
 * medacc_cost_centers — cost-centre master (SIFA §25 multi_cost_center).
 *
 * Journal lines are optionally allocated to a cost centre for departmental P&L.
 * `ref_id` binds a cost centre to an existing ClinicCore department
 * (clc_departments.id) or an ERP business_location (business_locations.id) — a
 * plain indexed column, no cross-table FK constraint (matches the module
 * convention of binding by id, not by schema-level FK).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medacc_cost_centers')) {
            return;
        }

        Schema::create('medacc_cost_centers', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->string('name', 191);
            $t->string('code', 40)->nullable();
            $t->enum('type', ['department', 'facility', 'project', 'other'])->default('department');
            $t->unsignedBigInteger('ref_id')->nullable(); // clc_departments.id / business_locations.id
            $t->boolean('is_active')->default(true);
            $t->timestamps();

            $t->unique(['business_id', 'code'], 'medacc_cc_biz_code_uq');
            $t->index(['business_id', 'type'], 'medacc_cc_biz_type_idx');
        });
    }

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