<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SystemBackup;
use App\Services\SystemBackupService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class BackupController extends Controller
{
    public function index(): View
    {
        return view('admin.backups', [
            'backups' => SystemBackup::query()->latest('id')->paginate(25),
        ]);
    }

    public function create(Request $request, SystemBackupService $backupService): RedirectResponse
    {
        $validated = $request->validate([
            'backup_type' => ['nullable', 'in:full'],
        ]);

        $backupService->create($validated['backup_type'] ?? 'full', auth()->id());

        return back()->with('status', 'Backup created successfully.');
    }

    public function download(int $backupId)
    {
        $backup = SystemBackup::query()->findOrFail($backupId);
        if (! Storage::disk('local')->exists($backup->file_path)) {
            return back()->withErrors(['backup' => 'Backup file missing.']);
        }

        return Storage::disk('local')->download($backup->file_path);
    }

    public function restore(Request $request, int $backupId, SystemBackupService $backupService): RedirectResponse
    {
        $validated = $request->validate([
            'confirm_code' => ['required', 'string'],
        ]);
        if (strtoupper($validated['confirm_code']) !== 'RESTORE') {
            return back()->withErrors(['confirm_code' => 'Type RESTORE to confirm restore action.']);
        }

        $backup = SystemBackup::query()->findOrFail($backupId);
        $backupService->restore($backup, auth()->id());

        return back()->with('status', 'Backup restored successfully.');
    }
}
