<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

/**
 * Creates the built-in "Local Storage" source (the existing public disk) and
 * points every existing tenant at it, so nothing breaks for tenants provisioned
 * before configurable storage. Local needs no credentials, so config stays null.
 */
return new class extends Migration
{
    public function up(): void
    {
        $id = DB::table('storage_sources')->insertGetId([
            'name' => 'Local Storage',
            'driver' => 'local',
            'config' => null,
            'quota_bytes' => null,
            'is_default' => true,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('tenants')->whereNull('storage_source_id')->update(['storage_source_id' => $id]);
    }

    public function down(): void
    {
        DB::table('tenants')->where('storage_source_id', function ($q) {
            $q->select('id')->from('storage_sources')->where('is_default', true)->limit(1);
        })->update(['storage_source_id' => null]);

        DB::table('storage_sources')->where('driver', 'local')->where('is_default', true)->delete();
    }
};
