<?php

namespace Database\Seeders;

use App\Models\Central\StorageSetting;
use App\Services\Storage\StorageConfig;
use Illuminate\Database\Seeder;

/**
 * Seeds the platform's singleton R2 configuration ({@see StorageSetting}) from
 * the CLOUDFLARE_R2_* environment values.
 *
 * Not required for storage to work — {@see StorageConfig}
 * already falls back to `.env` when the database row is empty — but running
 * this makes the credentials visible and editable in Master Control → Storage
 * immediately after a deploy, rather than only ever working invisibly from
 * `.env`.
 *
 * Idempotent and safe to re-run: it never overwrites a bucket/key that was
 * deliberately set through Master Control → Storage with a DIFFERENT value —
 * it only fills in fields left blank there, exactly like StorageConfig's own
 * per-field fallback. Re-running it after rotating `.env` credentials keeps
 * the stored row lined up unless an operator has since typed something else
 * into that field directly.
 */
class StorageSettingSeeder extends Seeder
{
    public function run(): void
    {
        $disk = (array) config('filesystems.disks.r2', []);

        if (blank($disk['key'] ?? null) || blank($disk['bucket'] ?? null)) {
            $this->command?->info('Cloudflare R2 credentials not set in .env — leaving storage_settings as is.');

            return;
        }

        $current = StorageSetting::current();
        $stored = $current?->decodedConfig() ?? [];

        $config = [
            'bucket' => $stored['bucket'] ?? $disk['bucket'] ?? null,
            'region' => $stored['region'] ?? $disk['region'] ?? 'auto',
            'endpoint' => $stored['endpoint'] ?? $disk['endpoint'] ?? null,
            'url' => $stored['url'] ?? $disk['url'] ?? null,
            'key' => $stored['key'] ?? $disk['key'] ?? null,
            'secret' => $stored['secret'] ?? $disk['secret'] ?? null,
        ];

        StorageSetting::writeConfig($config, $current?->quota_bytes);

        $this->command?->info('Seeded Cloudflare R2 ("'.$config['bucket'].'") into storage_settings.');
    }
}
