<?php

namespace App\Actions\Backup;

use App\Exceptions\BackupFailedException;
use Illuminate\Support\Facades\DB;
use ZipArchive;

class RestoreDatabaseBackupAction
{
    public function execute(string $zipFilePath): bool
    {
        if (!file_exists($zipFilePath)) {
            throw new BackupFailedException("File backup tidak ditemukan: {$zipFilePath}");
        }

        $zip = new ZipArchive();
        if ($zip->open($zipFilePath) !== true) {
            throw new BackupFailedException("File ZIP backup tidak valid atau rusak.");
        }

        $sqlContent = $zip->getFromName('database_dump.sql');

        if ($sqlContent === false) {
            // Coba cari file .sql lain dalam ZIP
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $filename = $zip->getNameIndex($i);
                if (pathinfo($filename, PATHINFO_EXTENSION) === 'sql') {
                    $sqlContent = $zip->getFromIndex($i);
                    break;
                }
            }
        }

        if (!$sqlContent) {
            throw new BackupFailedException("File database SQL tidak ditemukan di dalam paket ZIP.");
        }

        // Eksekusi SQL Query
        try {
            DB::unprepared($sqlContent);
            $zip->close();
            return true;
        } catch (\Throwable $e) {
            $zip->close();
            throw new BackupFailedException("Gagal memulihkan database: " . $e->getMessage());
        }
    }
}
