<?php

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

/**
 * SIFA P3-T7 — register the 'appointment.slot_available' MedNotify event + a
 * system-default in-app template so a freed slot (an appointment cancelled for a
 * doctor/date that has waitlisted patients) can fan out through the shared
 * notifications service (MedNotify README "Registering events from another
 * module").
 *
 * Entirely fail-soft: if MedNotify is NOT installed (its tables are absent) the
 * migration is a no-op. Uses raw-table upserts so we don't hard-depend on the
 * MedNotify entity classes at migrate time. Mirrors
 * 2026_07_03_0009_seed_patient_critical_alert_mednotify_event.
 */
class SeedSlotAvailableMednotifyEvent extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('mednotify_events') || !Schema::hasTable('mednotify_templates')) {
            return; // MedNotify not installed — nothing to register.
        }

        try {
            $now = now();

            $eventExists = \DB::table('mednotify_events')
                ->whereNull('business_id')
                ->where('event_key', 'appointment.slot_available')
                ->exists();

            if (!$eventExists) {
                \DB::table('mednotify_events')->insert([
                    'business_id'         => null,
                    'event_key'           => 'appointment.slot_available',
                    'module_key'          => 'ClinicCore',
                    'label'               => 'Appointment slot available',
                    'description'         => 'A slot opened up (a cancellation) matching a waitlisted patient.',
                    'default_channels'    => json_encode(['in_app']),
                    'available_variables' => json_encode([
                        ['name' => 'patient_name', 'label' => 'Patient name'],
                        ['name' => 'doctor_name',  'label' => 'Doctor name'],
                        ['name' => 'date',         'label' => 'Date'],
                        ['name' => 'link',         'label' => 'Booking link'],
                    ]),
                    'is_active'           => 1,
                    'created_at'          => $now,
                    'updated_at'          => $now,
                ]);
            }

            $tplExists = \DB::table('mednotify_templates')
                ->whereNull('business_id')
                ->where('event_key', 'appointment.slot_available')
                ->where('channel', 'in_app')
                ->exists();

            if (!$tplExists) {
                \DB::table('mednotify_templates')->insert([
                    'business_id' => null,
                    'event_key'   => 'appointment.slot_available',
                    'channel'     => 'in_app',
                    'subject'     => 'A slot has opened up',
                    'body'        => 'Good news {patient_name}: a slot with {doctor_name} on {date} is now available.',
                    'enabled'     => 1,
                    'created_at'  => $now,
                    'updated_at'  => $now,
                ]);
            }
        } catch (\Throwable $e) {
            // Column mismatch across MedNotify versions must never break migrate.
            \Log::warning('ClinicCore: appointment.slot_available MedNotify seed skipped: ' . $e->getMessage());
        }
    }

    public function down()
    {
        if (!Schema::hasTable('mednotify_events')) {
            return;
        }
        try {
            \DB::table('mednotify_templates')->whereNull('business_id')
                ->where('event_key', 'appointment.slot_available')->delete();
            \DB::table('mednotify_events')->whereNull('business_id')
                ->where('event_key', 'appointment.slot_available')->delete();
        } catch (\Throwable $e) {
            // ignore
        }
    }
}
