<?php

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

/**
 * mportal_dependents — family management (SIFA Phase 8, patient_portal).
 *
 * Links a GUARDIAN (the account holder = an ERP contacts.id, which is also the
 * PortalApi portal_owner) to one or more DEPENDENT patients (clc_patients.id).
 * Pediatrics / family accounts: a parent books & views records for a child.
 *
 * business_id-scoped. References into ERP/ClinicCore (contacts, clc_patients,
 * users) are plain indexed columns — no cross-table FK constraints — matching
 * the existing module convention (see Modules\MedBilling).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mportal_dependents')) {
            return;
        }

        Schema::create('mportal_dependents', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('guardian_contact_id');       // contacts.id (account holder / portal_owner)
            $t->unsignedInteger('dependent_patient_id');       // clc_patients.id
            $t->enum('relationship', ['child', 'spouse', 'parent', 'sibling', 'other'])->default('child');
            $t->boolean('can_book')->default(true);
            $t->boolean('can_view_records')->default(true);
            $t->unsignedInteger('created_by')->nullable();     // users.id (staff who linked)
            $t->timestamps();

            $t->index(['business_id', 'guardian_contact_id'], 'mportal_dep_biz_guardian_idx');
            $t->index(['business_id', 'dependent_patient_id'], 'mportal_dep_biz_patient_idx');
            $t->unique(['business_id', 'guardian_contact_id', 'dependent_patient_id'], 'mportal_dep_uq');
        });
    }

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