<?php

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

/**
 * Document header. Generic polymorphic attach (entity_type / entity_id) lets
 * ANY module attach documents to any of its records, plus an optional
 * contact_id patient link. current_version_id points at the latest row in
 * meddoc_versions (set after the first version is written).
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('meddoc_documents')) {
            Schema::create('meddoc_documents', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('doc_type_id');
                $t->string('title', 191);
                $t->string('entity_type', 191)->nullable(); // generic polymorphic attach
                $t->unsignedBigInteger('entity_id')->nullable();
                $t->unsignedInteger('contact_id')->nullable(); // ERP contact (patient) link
                $t->unsignedBigInteger('current_version_id')->nullable();
                $t->json('tags')->nullable();
                $t->enum('status', ['active', 'archived', 'deleted'])->default('active');
                $t->unsignedInteger('created_by')->nullable();
                $t->timestamps();
                $t->softDeletes();

                $t->index(['business_id', 'status']);
                $t->index(['business_id', 'doc_type_id']);
                $t->index(['business_id', 'contact_id']);
                $t->index(['business_id', 'entity_type', 'entity_id'], 'meddoc_documents_entity_idx');
            });
        }
    }

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