<?php

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

/**
 * Facility profile — 1:1 satellite of the core `business_locations` table
 * (spec §5 facility; REUSE-MAP §5 "extend via satellite table"; decision D5:
 * hierarchy lives here via parent_location_id, the core stays flat/leaf for
 * POS compatibility; max depth 5 is enforced in FacilityHierarchyService,
 * not in the DB).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('org_facility_profiles')) {
            return;
        }

        Schema::create('org_facility_profiles', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('business_location_id')->unique();
            $t->string('code', 20)->nullable();
            $t->enum('facility_type', [
                'hospital', 'clinic', 'lab', 'imaging', 'pharmacy',
                'dialysis', 'physio', 'diagnostic', 'other',
            ])->default('other');
            // Self-referencing via business_locations.id (NOT this table's id).
            $t->unsignedInteger('parent_location_id')->nullable();
            $t->json('working_hours')->nullable();   // per day of week, per department
            $t->json('capacity')->nullable();        // {beds, daily_outpatient, daily_lab_samples, daily_imaging}
            $t->decimal('geo_lat', 10, 7)->nullable();
            $t->decimal('geo_lng', 10, 7)->nullable();
            $t->json('modules_enabled')->nullable();
            $t->enum('status', ['active', 'inactive', 'under_construction'])->default('active');
            $t->json('metadata')->nullable();
            $t->timestamps();

            $t->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $t->foreign('business_location_id')->references('id')->on('business_locations')->onDelete('cascade');
            $t->index(['business_id', 'facility_type']);
            $t->index(['business_id', 'parent_location_id'], 'org_facility_parent_idx');
            $t->index(['business_id', 'code']);
        });
    }

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