<?php

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

/**
 * SIFA P5-T1 (radiology) — register the 'imaging.report.ready' MedNotify event +
 * a system-default in-app template so a finalised imaging report can fan out
 * through the shared notifications service (mirrors ClinicLab's
 * 'lab.result.ready' and ClinicCore's 'patient.critical_alert').
 *
 * Entirely fail-soft: if MedNotify is NOT installed (its tables are absent) the
 * migration is a no-op. Raw-table upserts avoid a migrate-time hard dependency on
 * the MedNotify entity classes.
 */
class SeedImagingReportReadyMednotifyEvent 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', 'imaging.report.ready')
                ->exists();

            if (!$eventExists) {
                \DB::table('mednotify_events')->insert([
                    'business_id'         => null,
                    'event_key'           => 'imaging.report.ready',
                    'module_key'          => 'ClinicCore',
                    'label'               => 'Imaging report ready',
                    'description'         => 'A radiology / imaging report was finalised for a patient.',
                    'default_channels'    => json_encode(['in_app']),
                    'available_variables' => json_encode([
                        ['name' => 'patient_name', 'label' => 'Patient name'],
                        ['name' => 'modality',     'label' => 'Modality'],
                        ['name' => 'ref_no',       'label' => 'Imaging ref no.'],
                        ['name' => 'impression',   'label' => 'Impression'],
                        ['name' => 'link',         'label' => 'Report link'],
                    ]),
                    'is_active'           => 1,
                    'created_at'          => $now,
                    'updated_at'          => $now,
                ]);
            }

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

            if (!$tplExists) {
                \DB::table('mednotify_templates')->insert([
                    'business_id' => null,
                    'event_key'   => 'imaging.report.ready',
                    'channel'     => 'in_app',
                    'subject'     => 'Imaging report ready',
                    'body'        => 'Imaging report for {patient_name} ({modality}, {ref_no}) is ready: {impression}',
                    'enabled'     => 1,
                    'created_at'  => $now,
                    'updated_at'  => $now,
                ]);
            }
        } catch (\Throwable $e) {
            // Column mismatch across MedNotify versions must never break migrate.
            \Log::warning('ClinicCore: imaging.report.ready 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', 'imaging.report.ready')->delete();
            \DB::table('mednotify_events')->whereNull('business_id')
                ->where('event_key', 'imaging.report.ready')->delete();
        } catch (\Throwable $e) {
            // ignore
        }
    }
}
