<?php

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

/**
 * medbill_patient_policies — a patient's coverage under a payer.
 *
 * Links optionally to a Wave-A clc_patient_insurances card row
 * (clc_patient_insurance_id) so scanned card info stays the source of truth for
 * card numbers while the policy holds the billing terms (coverage_pct,
 * copay_fixed, annual_limit). patient_id -> clc_patients, contact_id -> contacts.
 *
 * business_id-scoped; ERP/ClinicCore references are plain indexed columns.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medbill_patient_policies')) {
            return;
        }

        Schema::create('medbill_patient_policies', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedBigInteger('payer_id');
            $t->unsignedInteger('clc_patient_insurance_id')->nullable(); // Wave A card row
            $t->unsignedInteger('patient_id');                           // clc_patients.id
            $t->unsignedInteger('contact_id');                           // contacts.id (the payer-of-record)
            $t->string('policy_number', 100);
            $t->string('plan_name', 150)->nullable();
            $t->decimal('coverage_pct', 5, 2)->default(100);             // payer share %
            $t->decimal('copay_fixed', 15, 4)->default(0);
            $t->decimal('annual_limit', 15, 4)->nullable();
            $t->date('effective_from')->nullable();
            $t->date('expiry_date')->nullable();
            $t->enum('status', ['active', 'expired', 'cancelled'])->default('active');
            $t->timestamps();

            $t->index(['business_id', 'patient_id', 'status'], 'medbill_policies_biz_patient_idx');
            $t->index(['business_id', 'payer_id'], 'medbill_policies_biz_payer_idx');
            $t->index('clc_patient_insurance_id', 'medbill_policies_card_idx');
        });
    }

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