<?php

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

/**
 * Polymorphic alert feed for active admissions. Populated by the
 * vetadmission:check-overdue cron (overdue care slots, overdue meds,
 * abnormal/critical vitals, fluid bag past estimated end).
 *
 * Open alerts surface in the admission show banner + dashboard tile;
 * acknowledged alerts stay for audit.
 */
class CreateVaAlertsTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('va_alerts')) return;

        Schema::create('va_alerts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id')->index();
            $table->unsignedInteger('admission_id')->index();
            $table->enum('severity', ['info', 'warn', 'critical'])->default('warn')->index();
            $table->string('source', 30);                 // overdue_task | overdue_med | vital_abnormal | vital_critical | fluid_overdue
            $table->string('source_ref', 60)->nullable(); // e.g. plan_id|date|slot
            $table->string('message', 255);
            $table->dateTime('raised_at');
            $table->dateTime('acknowledged_at')->nullable();
            $table->unsignedInteger('acknowledged_by')->nullable();
            $table->timestamps();

            $table->index(['admission_id', 'acknowledged_at']);
            $table->unique(['admission_id', 'source', 'source_ref'], 'va_alerts_dedup');
        });
    }

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