<?php

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

/**
 * Insert-only audit trail — every view / download / print / share / upload /
 * delete against a document is logged here at the document layer, so the trail
 * is complete regardless of which storage backend physically holds the file
 * (spec §8: "audit trail of every view/download/print"). This is the document
 * layer complementing SmartStorage's file-layer ss_access_logs.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('meddoc_access_logs')) {
            Schema::create('meddoc_access_logs', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('document_id');
                $t->unsignedBigInteger('version_id')->nullable();
                $t->unsignedInteger('user_id')->nullable(); // null = public share access
                $t->enum('action', ['view', 'download', 'print', 'upload', 'share', 'delete']);
                $t->string('ip', 64)->nullable();
                $t->string('user_agent', 255)->nullable();
                $t->timestamp('created_at')->nullable();

                $t->index(['business_id', 'document_id']);
                $t->index(['business_id', 'action']);
                $t->index(['business_id', 'created_at']);
            });
        }
    }

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