<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;

/**
 * Item 1.3 + 4.1: flag appointments that have any out-of-range vital or
 * critical body-system finding so the Medical Critical Check report
 * can query them with a flat WHERE without re-evaluating logic.
 *
 *   vitals_critical_count   - integer (number of vitals outside the
 *                             critical bound for this species/age)
 *   vitals_abnormal_count   - integer (vitals merely low/high but not critical)
 *   vitals_critical_json    - per-vital severity snapshot so the report
 *                             can show "temperature 41.5°C (critical high)"
 *                             without re-reading the ranges table.
 *   findings_critical_count - integer (count of clc_appointment_exam_findings
 *                             with is_critical=1 on this appointment) -
 *                             updated whenever a finding is saved.
 *   last_critical_check_at  - timestamp so we know when the assessment
 *                             last ran (useful for re-evaluation jobs).
 */
class ClcAddCriticalFlagsToAppointments extends Migration
{
    public function up()
    {
        if (!Schema::hasColumn('clc_appointments', 'vitals_critical_count')) {
            Schema::table('clc_appointments', function (Blueprint $table) {
                $table->unsignedTinyInteger('vitals_critical_count')->default(0)->index();
                $table->unsignedTinyInteger('vitals_abnormal_count')->default(0);
                $table->json('vitals_critical_json')->nullable();
                $table->unsignedSmallInteger('findings_critical_count')->default(0)->index();
                $table->timestamp('last_critical_check_at')->nullable();
            });
        }

        Permission::findOrCreate('clinic.view_critical_report', 'web');
    }

    public function down()
    {
        if (Schema::hasColumn('clc_appointments', 'vitals_critical_count')) {
            Schema::table('clc_appointments', function (Blueprint $table) {
                $table->dropColumn([
                    'vitals_critical_count',
                    'vitals_abnormal_count',
                    'vitals_critical_json',
                    'findings_critical_count',
                    'last_critical_check_at',
                ]);
            });
        }
        Permission::where('name', 'clinic.view_critical_report')->delete();
    }
}
