<?php

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

/**
 * Version chain over the stored files (spec §8 versioning). Each row is one
 * physical file on the resolved disk. storage_disk records which disk the file
 * lives on so retrieval resolves the right adapter even if the tenant later
 * switches backends.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('meddoc_versions')) {
            Schema::create('meddoc_versions', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedBigInteger('document_id');
                $t->unsignedInteger('version_no');
                $t->string('file_path', 500);
                $t->string('original_name', 255);
                $t->string('mime', 191)->nullable();
                $t->unsignedBigInteger('size_bytes')->default(0);
                $t->string('storage_disk', 100)->nullable();
                $t->string('checksum', 191)->nullable();
                $t->unsignedInteger('uploaded_by')->nullable();
                $t->text('notes')->nullable();
                $t->timestamp('created_at')->nullable();

                $t->foreign('document_id')->references('id')->on('meddoc_documents')->onDelete('cascade');
                $t->index(['document_id', 'version_no']);
            });
        }
    }

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