<?php

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

/**
 * SIFA P5-T1 (radiology) — structured imaging reports.
 *
 * One report per imaging request (radiologist interpretation). The legacy free
 * text `clc_imaging_requests.report` column is left untouched; this richer entity
 * lives alongside it and is reached from the report-editor screen. Report lifecycle:
 * draft → preliminary → final → amended. On FINAL with a critical finding the
 * radiologist must record who the critical finding was communicated to, which
 * raises a MedicalAlertService critical_value alert and fans out via MedNotify.
 *
 * Additive + guarded: the create is wrapped in hasTable so re-running is safe.
 */
class CreateClcImagingReportsTable extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_imaging_reports')) {
            Schema::create('clc_imaging_reports', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->index();
                $table->unsignedInteger('imaging_request_id')->unique();
                $table->unsignedInteger('patient_id')->index();
                $table->unsignedInteger('radiologist_id')->nullable();   // clc_doctors.id

                $table->json('structured_findings')->nullable();          // [{region, finding, abnormality}]
                $table->text('narrative_findings')->nullable();
                $table->text('impression')->nullable();
                $table->text('recommendation')->nullable();
                $table->text('comparison')->nullable();                    // reference to prior studies

                $table->boolean('has_critical')->default(false);
                $table->text('critical_description')->nullable();
                $table->string('critical_communicated_to', 191)->nullable();
                $table->timestamp('critical_communicated_at')->nullable();

                $table->enum('report_status', ['draft', 'preliminary', 'final', 'amended'])
                      ->default('draft')->index();
                $table->unsignedInteger('signed_by')->nullable();
                $table->timestamp('signed_at')->nullable();
                $table->timestamp('amended_at')->nullable();
                $table->text('amendment_reason')->nullable();

                $table->timestamps();
            });
        }

        foreach (['clinic.imaging.report', 'clinic.imaging.verify'] as $perm) {
            Permission::findOrCreate($perm, 'web');
        }
    }

    public function down()
    {
        Schema::dropIfExists('clc_imaging_reports');
        Permission::whereIn('name', ['clinic.imaging.report', 'clinic.imaging.verify'])->delete();
    }
}
