<?php

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

/**
 * mportal_record_releases — controls what a patient can see in the portal
 * (SIFA Phase 8, patient_portal → medical_records).
 *
 * Per spec, clinical notes are visible ONLY after provider release; labs /
 * imaging / prescriptions / vitals are visible by default. A row here is an
 * OVERRIDE of the config default (Config/config.php → release_defaults):
 * released=true reveals a type early, released=false hides one that is normally
 * visible. RecordAccessService reads these rows.
 *
 * One row per (business_id, patient_id, record_type). business_id-scoped;
 * patient_id references clc_patients.id (plain indexed column, no FK).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mportal_record_releases')) {
            return;
        }

        Schema::create('mportal_record_releases', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('patient_id');                 // clc_patients.id
            $t->enum('record_type', [
                'clinical_note', 'lab_result', 'imaging_report', 'prescription', 'vitals', 'full',
            ]);
            $t->boolean('released')->default(false);
            $t->unsignedInteger('released_by')->nullable();    // users.id
            $t->timestamp('released_at')->nullable();
            $t->string('notes', 255)->nullable();
            $t->timestamps();

            $t->index(['business_id', 'patient_id'], 'mportal_rel_biz_patient_idx');
            $t->unique(['business_id', 'patient_id', 'record_type'], 'mportal_rel_uq');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('mportal_record_releases');
    }
};
