<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

/**
 * Backfill: vital critical flags were left at 0 for appointments saved
 * before the species-alias fix (dog -> canine). Re-evaluate vitals for
 * every appointment that has at least one vital recorded so the
 * Medical Critical Check report (item 4.1) immediately shows historical
 * critical visits without waiting for the consultation to be re-saved.
 *
 * Safe to re-run: the recompute is idempotent (overwrites the flag
 * columns from the current vitals). Skips silently if the columns
 * don't exist yet.
 */
class ClcBackfillVitalCriticalFlags extends Migration
{
    public function up()
    {
        if (!\Schema::hasColumn('clc_appointments', 'vitals_critical_count')) return;

        \Modules\ClinicCore\Entities\ClcAppointment::query()
            ->where(function ($q) {
                $q->whereNotNull('temperature')
                  ->orWhereNotNull('heart_rate')
                  ->orWhereNotNull('respiratory_rate')
                  ->orWhereNotNull('weight_kg');
            })
            ->chunkById(200, function ($appts) {
                foreach ($appts as $appt) {
                    try {
                        $patient = $appt->pet;
                        $species = $patient ? strtolower($patient->species ?? '') : null;
                        $ageYears = ($patient && $patient->dob)
                            ? (int) \Carbon\Carbon::parse($patient->dob)->diffInYears(now())
                            : null;
                        $vitals = [
                            'temperature'      => $appt->temperature,
                            'heart_rate'       => $appt->heart_rate,
                            'respiratory_rate' => $appt->respiratory_rate,
                            'weight_kg'        => $appt->weight_kg,
                        ];
                        $range = \Modules\ClinicCore\Entities\ClcVitalRange::resolve(
                            (int) $appt->business_id, $species, $ageYears
                        );
                        $annotation = $range ? $range->annotate($vitals) : [];
                        $critCount = 0; $abnCount = 0;
                        foreach ($annotation as $sev) {
                            if ($sev === 'critical')                $critCount++;
                            elseif (in_array($sev, ['low','high'])) $abnCount++;
                        }
                        $findingsCrit = (int) DB::table('clc_appointment_exam_findings')
                            ->where('appointment_id', $appt->id)
                            ->where('is_critical', 1)
                            ->count();
                        $appt->forceFill([
                            'vitals_critical_count'   => $critCount,
                            'vitals_abnormal_count'   => $abnCount,
                            'vitals_critical_json'    => $annotation ? json_encode($annotation) : null,
                            'findings_critical_count' => $findingsCrit,
                            'last_critical_check_at'  => now(),
                        ])->save();
                    } catch (\Throwable $e) {
                        \Log::warning('Backfill critical-flags failed for appt #' . $appt->id . ': ' . $e->getMessage());
                    }
                }
            });
    }

    public function down() { /* no rollback - data backfill only */ }
}
