<?php

namespace App\Services\Backup;

use App\Models\BackupDestination;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Throwable;

class BackupDestinationTester
{
    public function __construct(private BackupDestinationRegistrar $registrar) {}

    /** Kaydedilmemiş driver+config ile test (test-connection butonu). */
    public function test(string $driver, array $config): array
    {
        $dummy = new BackupDestination(['driver' => $driver]);
        $dummy->config = $config;

        return $this->testDiskConfig($this->registrar->diskConfig($dummy));
    }

    /** Verilen Flysystem disk config'iyle probe yaz/oku/sil. */
    public function testDiskConfig(array $diskConfig): array
    {
        $probe = '.procp-backup-test-'.Str::uuid();
        $content = 'ok';
        $disk = null;

        try {
            $disk = Storage::build($diskConfig);
            $disk->put($probe, $content);
            $read = $disk->get($probe);

            if ($read !== $content) {
                return ['ok' => false, 'message' => 'Probe içeriği eşleşmedi.'];
            }

            return ['ok' => true, 'message' => 'Bağlantı başarılı.'];
        } catch (Throwable $e) {
            return ['ok' => false, 'message' => $e->getMessage()];
        } finally {
            try {
                $disk?->delete($probe);
            } catch (Throwable) {
                // cleanup best-effort; probe silme hatası test sonucunu etkilemez
            }
        }
    }

    /** Kaydedilmiş hedefi test et + last_test_* güncelle. */
    public function testAndRecord(BackupDestination $dest): array
    {
        $result = $this->testDiskConfig($this->registrar->diskConfig($dest));
        $dest->forceFill(['last_test_at' => now(), 'last_test_ok' => $result['ok']])->save();

        return $result;
    }
}
