<?php

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

/**
 * medbill_charge_items — the charge-capture staging area (spec §22 charge_capture).
 *
 * ChargeCaptureService drafts rows here from ClinicCore encounters, unbilled
 * clc_order_items, and dispensed clc_prescription_items. When billed, ONE ERP
 * sell is created per patient via TransactionUtil and transaction_id /
 * transaction_sell_line_id are written back on each row (status -> billed).
 *
 * product_id / variation_id are set only when the charge resolves to a real ERP
 * product (consultation fee via clc_doctors.product_id, dispensed medicine via
 * clc_medicines.product_id). Rows without a resolvable product keep unit_price
 * from the source but cannot be pushed as ERP sell lines (flagged in the UI).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medbill_charge_items')) {
            return;
        }

        Schema::create('medbill_charge_items', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('appointment_id')->nullable();       // clc_appointments.id
            $t->unsignedInteger('patient_id');                       // clc_patients.id
            $t->enum('source_type', ['clc_appointment', 'clc_order_item', 'clc_prescription_item', 'manual']);
            $t->unsignedInteger('source_id')->nullable();            // id of the source row
            $t->string('description', 255);
            $t->unsignedInteger('product_id')->nullable();           // ERP products.id when resolvable
            $t->unsignedInteger('variation_id')->nullable();         // ERP variations.id when resolvable
            $t->decimal('qty', 15, 4)->default(1);
            $t->decimal('unit_price', 15, 4)->default(0);
            $t->enum('status', ['draft', 'billed', 'voided'])->default('draft');
            $t->unsignedInteger('transaction_id')->nullable();       // ERP transactions.id once billed
            $t->unsignedInteger('transaction_sell_line_id')->nullable();
            $t->unsignedInteger('created_by')->nullable();           // users.id
            $t->timestamps();

            $t->index(['business_id', 'patient_id', 'status'], 'medbill_charges_biz_patient_idx');
            $t->index(['business_id', 'appointment_id'], 'medbill_charges_biz_appt_idx');
            $t->index(['business_id', 'source_type', 'source_id'], 'medbill_charges_source_idx');
            $t->index('transaction_id', 'medbill_charges_txn_idx');
        });
    }

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