<?php

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

/**
 * medbill_payers — the payer master (insurance / corporate / government / other).
 *
 * Audit decision D8: payers are a DEDICATED table, NOT ERP contacts. A payer may
 * carry its own ERP selling_price_groups price list (default_price_group_id) so
 * claimed prices follow the payer's negotiated rates.
 *
 * business_id-scoped. References into ERP core tables (business,
 * selling_price_groups) are plain indexed columns — no cross-table FK
 * constraints — matching the existing module convention (see Modules\MedNotify).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medbill_payers')) {
            return;
        }

        Schema::create('medbill_payers', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->string('name', 191);
            $t->string('code', 60)->nullable();
            $t->enum('payer_type', ['insurance', 'corporate', 'government', 'other'])->default('insurance');
            $t->json('contact')->nullable();                          // {phone, email, address, portal_url…}
            $t->unsignedInteger('default_price_group_id')->nullable(); // FK selling_price_groups (payer price list)
            $t->enum('claim_submission', ['portal', 'email', 'edi', 'paper'])->default('paper');
            $t->boolean('pre_auth_required_default')->default(false);
            $t->integer('settlement_terms_days')->nullable();
            $t->boolean('is_active')->default(true);
            $t->timestamps();

            $t->index(['business_id', 'is_active'], 'medbill_payers_biz_active_idx');
            $t->index(['business_id', 'payer_type'], 'medbill_payers_biz_type_idx');
            $t->unique(['business_id', 'code'], 'medbill_payers_biz_code_uq');
        });
    }

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