<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('care_specialty_clinical_records')) {
            return;
        }

        Schema::create('care_specialty_clinical_records', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->string('owner_ref', 64)->index();
            $table->foreignId('organization_id')->constrained('care_organizations')->cascadeOnDelete();
            $table->foreignId('branch_id')->nullable()->constrained('care_branches')->nullOnDelete();
            $table->foreignId('visit_id')->constrained('care_visits')->cascadeOnDelete();
            $table->foreignId('patient_id')->constrained('care_patients')->cascadeOnDelete();
            $table->foreignId('consultation_id')->nullable()->constrained('care_consultations')->nullOnDelete();
            $table->string('module_key', 64)->index();
            $table->string('record_type', 64);
            $table->string('status', 32)->default('draft')->index();
            $table->string('stage_code', 64)->nullable();
            $table->json('payload')->nullable();
            $table->json('alerts')->nullable();
            $table->string('recorded_by')->nullable();
            $table->timestamp('recorded_at')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['visit_id', 'module_key', 'record_type'], 'care_specialty_clinical_unique');
            $table->index(['organization_id', 'module_key', 'status']);
        });
    }

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