<?php

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

return new class extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('ss_files')) {
            Schema::create('ss_files', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->unsignedInteger('business_id')->nullable()->index();

                // The path the application thinks it wrote/reads (relative to the
                // target disk root), e.g. "media/1696_..._photo.jpg".
                $table->string('logical_path', 500)->index();

                // Where the bytes actually live.
                $table->string('backend', 50);            // local|s3|dropbox|gdrive|laravel-default
                $table->string('backend_path', 500);

                // at-rest encryption metadata
                $table->boolean('is_encrypted')->default(false);
                $table->string('enc_algo', 30)->nullable();
                $table->string('enc_iv', 64)->nullable();   // hex/base64 nonce
                $table->string('enc_tag', 64)->nullable();  // GCM auth tag

                $table->string('mime', 191)->nullable();
                $table->unsignedBigInteger('size')->nullable();          // plaintext size
                $table->unsignedBigInteger('stored_size')->nullable();   // ciphertext size on backend
                $table->string('checksum', 64)->nullable();

                $table->unsignedInteger('uploaded_by')->nullable();
                $table->timestamps();

                $table->unique(['logical_path', 'business_id'], 'ss_files_logical_unique');
            });
        }
    }

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