<?php

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

/**
 * Inpatient placement: visit ↔ care unit / bed + stay history.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('care_visits', function (Blueprint $table) {
            $table->foreignId('care_unit_id')->nullable()->after('patient_id')
                ->constrained('care_care_units')->nullOnDelete();
            $table->foreignId('bed_id')->nullable()->after('care_unit_id')
                ->constrained('care_beds')->nullOnDelete();
            $table->timestamp('placed_at')->nullable()->after('bed_id');
            $table->string('placed_by')->nullable()->after('placed_at');
            $table->index(['care_unit_id', 'status']);
            $table->index(['bed_id']);
        });

        Schema::create('care_bed_stays', function (Blueprint $table) {
            $table->id();
            $table->string('owner_ref')->index();
            $table->foreignId('organization_id')->constrained('care_organizations')->cascadeOnDelete();
            $table->foreignId('visit_id')->constrained('care_visits')->cascadeOnDelete();
            $table->foreignId('care_unit_id')->constrained('care_care_units')->cascadeOnDelete();
            $table->foreignId('bed_id')->nullable()->constrained('care_beds')->nullOnDelete();
            /** active | ended */
            $table->string('status')->default('active');
            $table->timestamp('admitted_at');
            $table->timestamp('discharged_at')->nullable();
            $table->string('admitted_by')->nullable();
            $table->string('discharged_by')->nullable();
            $table->string('reason')->nullable(); // admit | transfer | discharge
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->index(['care_unit_id', 'status']);
            $table->index(['bed_id', 'status']);
            $table->index(['visit_id', 'status']);
        });
    }

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

        Schema::table('care_visits', function (Blueprint $table) {
            $table->dropConstrainedForeignId('bed_id');
            $table->dropConstrainedForeignId('care_unit_id');
            $table->dropColumn(['placed_at', 'placed_by']);
        });
    }
};
