<?php

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

/**
 * VetAdmission M2 — weight-based dose calculator + IV fluid tracking.
 *
 *  va_admission_medications      : prescribed orders for the admission
 *  va_medication_administrations : per-dose due/given log
 *  va_admission_fluids           : current IV fluid bag + rate
 *  va_fluid_bag_changes          : history of bag swaps
 *
 * Doses can be saved as (mg/kg) OR (mg total) OR (volume ml) — the
 * calculator on the UI picks the right anchor based on what's known
 * (pet weight, medicine concentration).
 */
class CreateVaMedicationsAndFluids extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('va_admission_medications')) {
            Schema::create('va_admission_medications', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('admission_id')->index();
                $table->unsignedInteger('medicine_id')->nullable();   // vc_medicines.id
                $table->string('medicine_name', 150);                 // snapshot, free-text fallback
                $table->enum('route', ['PO','IV','SC','IM','topical','inhalation','PR','other'])->default('PO');
                $table->decimal('dose_mg_per_kg', 10, 4)->nullable();
                $table->decimal('dose_total_mg',  10, 4)->nullable();
                $table->decimal('concentration_mg_per_ml', 10, 4)->nullable();
                $table->decimal('volume_per_dose_ml', 10, 4)->nullable();    // computed snapshot
                $table->decimal('weight_kg_used', 8, 2)->nullable();         // weight at order time
                $table->unsignedTinyInteger('frequency_hours')->default(8);  // q4h/q6h/q8h/q12h/q24h
                $table->unsignedSmallInteger('duration_hours')->nullable(); // null = open-ended
                $table->dateTime('start_at');
                $table->dateTime('end_at')->nullable();
                $table->string('notes', 500)->nullable();
                $table->boolean('active')->default(true);
                $table->unsignedInteger('created_by')->nullable();
                $table->timestamps();

                $table->index(['admission_id', 'active']);
            });
        }

        if (!Schema::hasTable('va_medication_administrations')) {
            Schema::create('va_medication_administrations', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('admission_medication_id')->index();
                $table->dateTime('due_at');
                $table->dateTime('administered_at')->nullable();
                $table->decimal('actual_volume_ml', 10, 4)->nullable();
                $table->decimal('actual_dose_mg',   10, 4)->nullable();
                $table->enum('status', ['pending','given','missed','refused','rescheduled'])->default('pending');
                $table->unsignedInteger('given_by')->nullable();
                $table->string('notes', 500)->nullable();
                $table->timestamps();

                // Explicit shortened name — MySQL caps identifiers at 64 chars
                // and the auto-name (va_medication_administrations_admission_medication_id_due_at_index)
                // exceeds that limit.
                $table->index(['admission_medication_id', 'due_at'], 'va_medadmin_med_due_idx');
            });
        }

        if (!Schema::hasTable('va_admission_fluids')) {
            Schema::create('va_admission_fluids', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('admission_id')->index();
                $table->string('fluid_type', 80);                       // LRS, NaCl 0.9%, Dextrose 5%, ...
                $table->decimal('rate_ml_per_hr', 8, 2);
                $table->decimal('rate_ml_per_kg_per_hr', 6, 2)->nullable();
                $table->decimal('bag_size_ml', 8, 2);
                $table->dateTime('started_at');
                $table->dateTime('estimated_end_at')->nullable();
                $table->dateTime('ended_at')->nullable();
                $table->decimal('total_volume_given_ml', 10, 2)->default(0);
                $table->string('notes', 500)->nullable();
                $table->boolean('active')->default(true);
                $table->unsignedInteger('created_by')->nullable();
                $table->timestamps();

                $table->index(['admission_id', 'active']);
            });
        }

        if (!Schema::hasTable('va_fluid_bag_changes')) {
            Schema::create('va_fluid_bag_changes', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('fluid_id')->index();
                $table->dateTime('changed_at');
                $table->decimal('new_bag_size_ml', 8, 2);
                $table->decimal('volume_consumed_ml', 10, 2)->nullable();
                $table->unsignedInteger('given_by')->nullable();
                $table->string('notes', 500)->nullable();
                $table->timestamps();
            });
        }
    }

    public function down()
    {
        Schema::dropIfExists('va_fluid_bag_changes');
        Schema::dropIfExists('va_admission_fluids');
        Schema::dropIfExists('va_medication_administrations');
        Schema::dropIfExists('va_admission_medications');
    }
}
