<?php

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

/**
 * Assigns each tenant to a storage source and caches its computed usage so the
 * master-control dashboard never has to list objects against S3/R2 per request.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('tenants', function (Blueprint $table) {
            $table->foreignId('storage_source_id')->nullable()->after('trial_ends_at')
                ->constrained('storage_sources')->nullOnDelete();
            $table->unsignedBigInteger('storage_used_bytes')->default(0)->after('storage_source_id');
            $table->unsignedInteger('storage_files_count')->default(0)->after('storage_used_bytes');
            $table->timestamp('storage_calculated_at')->nullable()->after('storage_files_count');
        });
    }

    public function down(): void
    {
        Schema::table('tenants', function (Blueprint $table) {
            $table->dropConstrainedForeignId('storage_source_id');
            $table->dropColumn(['storage_used_bytes', 'storage_files_count', 'storage_calculated_at']);
        });
    }
};
