<?php

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

/**
 * medsx_checklists — the WHO Surgical Safety Checklist per case, one row per phase
 * (SIFA spec §16 surgery > surgical_safety_checklist). Sign In / Time Out / Sign
 * Out. `items` is [{label, checked, by}]; the default item set for each phase is
 * seeded on case creation from SurgeryService::CHECKLIST_ITEMS. The Time Out phase
 * is the mandatory gate before a case can move to in_or.
 *
 * unique(case_id, phase) — exactly one checklist row per phase per case.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medsx_checklists')) {
            return;
        }

        Schema::create('medsx_checklists', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedBigInteger('case_id');                     // medsx_cases
            $t->enum('phase', ['sign_in', 'time_out', 'sign_out']);
            $t->json('items')->nullable();                         // [{label, checked, by}]
            $t->unsignedInteger('completed_by')->nullable();       // users.id (the signer)
            $t->timestamp('completed_at')->nullable();
            $t->timestamps();

            $t->unique(['case_id', 'phase'], 'medsx_checklists_case_phase_uq');
            $t->index(['business_id', 'case_id'], 'medsx_checklists_biz_case_idx');
        });
    }

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