<?php

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

/**
 * mportal_questionnaires — health-questionnaire definitions (SIFA Phase 8,
 * patient_portal → health_tools → health_questionnaires).
 *
 * The seeder ships two SYSTEM rows (business_id NULL): the standard PHQ-9 and
 * GAD-7 instruments (items + scoring bands). A business may also add its own
 * `custom` questionnaires (business_id set). `items` is a JSON array of
 * {q, options:[{label,value}]}; `scoring` is the band map read by
 * QuestionnaireService.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mportal_questionnaires')) {
            return;
        }

        Schema::create('mportal_questionnaires', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id')->nullable();    // NULL = system (PHQ-9/GAD-7)
            $t->enum('code', ['phq9', 'gad7', 'custom'])->default('custom');
            $t->string('title', 191);
            $t->json('items');                                  // [{q, options:[{label,value}]}]
            $t->json('scoring')->nullable();                    // {bands:[{min,max,severity}], max_score}
            $t->boolean('is_active')->default(true);
            $t->timestamps();

            $t->index(['business_id', 'code'], 'mportal_q_biz_code_idx');
        });
    }

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