<?php

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

/**
 * Replaces the terse one-liners on the seeded system protocols with full
 * clinical descriptions: indication, what the bundle does, monitoring, and
 * red-flag escalation. Only touches rows where business_id IS NULL so any
 * business-cloned copies keep whatever the clinic wrote.
 */
class EnrichDefaultProtocolDescriptions extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('va_protocols')) return;

        $map = [
            'Canine Parvo' =>
"Indication: Canine parvovirus enteritis (PCR / SNAP positive, or strongly suspicious history — unvaccinated puppy with severe vomiting / haemorrhagic diarrhoea / leukopenia).

What this protocol does:
• High-rate IV crystalloid (LRS) to correct dehydration and ongoing GI losses
• Anti-emetic cover (maropitant q24h IV) for nausea + protection from oesophagitis
• Broad-spectrum IV antibiotic (ampicillin q8h) to cover for bacterial translocation across damaged gut mucosa
• Round-the-clock temperature monitoring (q4h) — the only one of the system protocols with full 24-hour vitals coverage

Monitoring: temperature q4h, PCV/TS daily, glucose if collapsed.
Escalate to ICU / extended care if: persistent vomiting after 24h of treatment, sustained hypoglycaemia, sepsis signs (hypothermia, hypotension), or sudden collapse.",

            'Feline URI' =>
"Indication: Feline upper respiratory infection (calicivirus / herpesvirus / chlamydophila) presenting with sneezing, oculonasal discharge, anorexia, and mild-to-moderate dehydration in an otherwise stable cat.

What this protocol does:
• Doxycycline PO q24h × 10 days — primary cover for Chlamydophila felis and Mycoplasma
• Nasal cleaning q8h — keeps the airway patent and improves appetite
• Appetite check q12h — anorexia is the highest-risk complication of feline URI

Notes: this is the lowest-intensity system protocol — there are no IV fluids and no IV medications. Use it for inpatients well enough to eat with encouragement and stay hydrated voluntarily.
Escalate if: anorexia > 24 hours, dehydration > 5%, marked dyspnoea, or eye involvement worsens — switch to IV support + ophthalmic care.",

            'Post-op orthopedic' =>
"Indication: Standard recovery for any orthopedic surgical patient (TPLO, fracture repair, joint surgery, etc.) staying overnight or longer for pain control and observation.

What this protocol does:
• Meloxicam PO q24h × 5 days — NSAID analgesia. Add an opioid (e.g. methadone, buprenorphine) separately for the first 24-48 h if pain is moderate-to-severe.
• Cefazolin IV q8h × 48 h — perioperative antibiotic prophylaxis only. NOT a treatment of established infection.
• Wound check q6h — early detection of incision dehiscence, swelling, or discharge

Activity: strict crate rest. No discharge before the orthopedic surgeon clears the post-op films/exam.
Escalate if: incision opens / bleeds / discharges, lameness sharply worse instead of improving, refusal to eat past 24 h, or vomiting on NSAIDs.",

            'Diabetic ketoacidosis (DKA)' =>
"Indication: Diabetic ketoacidosis — hyperglycaemia + ketonuria/ketonaemia + metabolic acidosis. Typically presents with profound depression, dehydration, vomiting, and Kussmaul respiration.

What this protocol does:
• NaCl 0.9% maintenance fluid (NOT LRS — lactate complicates DKA management). Start with rehydration bolus separately; the protocol's 50 mL/h is the maintenance rate.
• Regular insulin CRI 0.05 IU/kg/hr — the most frequent medication interval in any system protocol (q1h dosing rows seeded for 24 h). Adjust the rate (not the dose) based on hourly glucose readings.
• Glucose monitoring q2h — protocol's highest-frequency monitoring task

Watch points:
• Drop in glucose > 75 mg/dL/hr is too fast — risk of cerebral oedema; halve the rate.
• Once glucose < 250 mg/dL, switch the maintenance fluid to include dextrose (NaCl + 2.5–5% dextrose) so the CRI can keep resolving the ketoacidosis without inducing hypoglycaemia.
• Hypokalaemia is the most common life-threatening electrolyte derangement during DKA treatment — supplement KCl in the fluids per the standard sliding scale once urine is being produced.
Escalate if: refractory acidosis, persistent hypokalaemia, neurological signs, or no improvement in 12 h.",
        ];

        foreach ($map as $name => $description) {
            DB::table('va_protocols')
                ->whereNull('business_id')
                ->where('name', $name)
                ->update(['description' => $description, 'updated_at' => now()]);
        }
    }

    public function down()
    {
        if (!Schema::hasTable('va_protocols')) return;

        $oldDescriptions = [
            'Canine Parvo' => 'Aggressive supportive care for parvovirus enteritis (IVF, antiemetic, antibiotics, monitoring).',
            'Feline URI'   => 'Upper respiratory infection — supportive care, eye/nose hygiene, appetite stimulant.',
            'Post-op orthopedic' => 'Standard post-op orthopedic recovery — pain control, antibiotic cover, mobility restriction.',
            'Diabetic ketoacidosis (DKA)' => 'Insulin CRI + electrolyte correction + frequent glucose monitoring.',
        ];
        foreach ($oldDescriptions as $name => $desc) {
            DB::table('va_protocols')
                ->whereNull('business_id')
                ->where('name', $name)
                ->update(['description' => $desc, 'updated_at' => now()]);
        }
    }
}
