<?php

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

/**
 * mportal_questionnaire_responses — a patient's answers to a questionnaire
 * (SIFA Phase 8, patient_portal → health_tools).
 *
 * Staff "send a questionnaire" by creating an EMPTY row (answers=null,
 * completed_at=null) which the patient later fills. On completion,
 * QuestionnaireService computes `score` + `severity` (e.g. PHQ-9 >=15 =
 * moderately severe). business_id-scoped; patient_id → clc_patients.id.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mportal_questionnaire_responses')) {
            return;
        }

        Schema::create('mportal_questionnaire_responses', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('patient_id');                 // clc_patients.id
            $t->unsignedBigInteger('questionnaire_id');        // mportal_questionnaires.id
            $t->json('answers')->nullable();                   // [{q_index, value}] — null until completed
            $t->integer('score')->nullable();
            $t->string('severity', 40)->nullable();
            $t->unsignedInteger('assigned_by')->nullable();    // users.id (staff who sent it)
            $t->timestamp('completed_at')->nullable();
            $t->timestamps();

            $t->index(['business_id', 'patient_id'], 'mportal_qr_biz_patient_idx');
            $t->index(['business_id', 'questionnaire_id'], 'mportal_qr_biz_q_idx');
        });
    }

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