<?php

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

/**
 * Drops the multi-source storage registry, replaced by the `storage_settings`
 * singleton (see 2026_08_11_000001_create_storage_settings_table.php).
 *
 * Every tenant now shares one platform-wide Cloudflare R2 bucket — there is
 * nothing left to assign a tenant to and nothing left to migrate between, so
 * `storage_sources`, `storage_migrations` and the FK column on `tenants` that
 * pointed at them are dead weight. `storage_migrations` and the FK column go
 * first: both reference `storage_sources`.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('tenants', function (Blueprint $table) {
            $table->dropConstrainedForeignId('storage_source_id');
        });

        Schema::dropIfExists('storage_migrations');
        Schema::dropIfExists('storage_sources');
    }

    public function down(): void
    {
        Schema::create('storage_sources', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('driver', 20);
            $table->text('config')->nullable();
            $table->unsignedBigInteger('quota_bytes')->nullable();
            $table->boolean('is_default')->default(false);
            $table->timestamps();
            $table->softDeletes();
        });

        Schema::create('storage_migrations', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('from_source_id')->nullable()->constrained('storage_sources')->nullOnDelete();
            $table->foreignId('to_source_id')->constrained('storage_sources')->cascadeOnDelete();
            $table->string('mode', 20);
            $table->boolean('backup')->default(false);
            $table->string('status', 20)->default('pending');
            $table->unsignedBigInteger('bytes_total')->default(0);
            $table->unsignedBigInteger('bytes_done')->default(0);
            $table->text('error')->nullable();
            $table->timestamps();
        });

        Schema::table('tenants', function (Blueprint $table) {
            $table->foreignId('storage_source_id')->nullable()
                ->constrained('storage_sources')->nullOnDelete();
        });
    }
};
