<?php

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

/**
 * PR 1 — Assessment engine schema (templates, questions, assessments, answers).
 * Scores: PR 4. Pathways: PR 5.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('care_assessment_templates', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            // v1 always NULL (system catalog). Reserved for future org forks.
            $table->foreignId('organization_id')->nullable()->constrained('care_organizations')->nullOnDelete();
            $table->string('code');
            $table->string('name');
            $table->string('category'); // universal, disease, outcome, screening
            $table->text('description')->nullable();
            $table->unsignedInteger('version')->default(1);
            $table->boolean('is_current')->default(true);
            $table->string('scoring_strategy')->nullable(); // sum_items, single_value, custom:Handler
            $table->json('meta')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
            $table->softDeletes();

            // Valid for v1 (system-only rows). Org clones out of scope.
            $table->unique(['code', 'version']);
            $table->index(['category', 'is_current', 'is_active']);
            $table->index(['code', 'is_current']);
        });

        Schema::create('care_assessment_questions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('template_id')->constrained('care_assessment_templates')->cascadeOnDelete();
            $table->string('code');
            $table->string('section')->nullable();
            $table->string('label');
            $table->text('help_text')->nullable();
            $table->string('answer_type'); // text, number, boolean, date, single_choice, multi_choice, score_item, calculated
            $table->json('options')->nullable();
            $table->boolean('is_required')->default(false);
            $table->unsignedInteger('sort_order')->default(0);
            $table->string('score_key')->nullable();
            $table->json('validation')->nullable();
            $table->timestamps();

            $table->unique(['template_id', 'code']);
            $table->index(['template_id', 'sort_order']);
        });

        Schema::create('care_assessments', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->string('owner_ref')->index();
            $table->foreignId('organization_id')->constrained('care_organizations')->cascadeOnDelete();
            $table->foreignId('branch_id')->nullable()->constrained('care_branches')->nullOnDelete();
            $table->foreignId('patient_id')->constrained('care_patients')->cascadeOnDelete();
            // Frozen template version for historical integrity.
            $table->foreignId('template_id')->constrained('care_assessment_templates')->restrictOnDelete();
            $table->foreignId('consultation_id')->nullable()->constrained('care_consultations')->nullOnDelete();
            $table->foreignId('visit_id')->nullable()->constrained('care_visits')->nullOnDelete();
            // patient_pathway_id added in PR 5 when pathway tables exist.
            $table->foreignId('practitioner_id')->nullable()->constrained('care_practitioners')->nullOnDelete();
            $table->string('status')->default('draft'); // draft, completed, cancelled
            $table->timestamp('assessed_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->string('completed_by')->nullable();
            $table->string('started_by')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index(['patient_id', 'assessed_at']);
            $table->index(['consultation_id']);
            $table->index(['owner_ref', 'status']);
            $table->index(['template_id', 'status']);
            $table->index(['patient_id', 'template_id', 'status']);
        });

        Schema::create('care_assessment_answers', function (Blueprint $table) {
            $table->id();
            $table->string('owner_ref')->index();
            $table->foreignId('assessment_id')->constrained('care_assessments')->cascadeOnDelete();
            $table->foreignId('question_id')->constrained('care_assessment_questions')->restrictOnDelete();
            $table->text('value_text')->nullable();
            $table->decimal('value_number', 12, 4)->nullable();
            $table->boolean('value_boolean')->nullable();
            $table->dateTime('value_date')->nullable();
            $table->json('value_json')->nullable();
            $table->timestamps();

            $table->unique(['assessment_id', 'question_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('care_assessment_answers');
        Schema::dropIfExists('care_assessments');
        Schema::dropIfExists('care_assessment_questions');
        Schema::dropIfExists('care_assessment_templates');
    }
};
