<?php

namespace App\Http\Controllers;

use App\Models\Backup;
use App\Models\Website;
use App\Repositories\BackupRepository;
use App\Services\BackupService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class BackupsController extends Controller
{
    public function __construct(
        protected BackupRepository $backups,
        protected BackupService $backupService,
    ) {
    }

    public function index(): View
    {
        return view('backups.index', [
            'backups' => $this->backups->paginate(request()->only('status', 'website')),
            'websites' => Website::query()->orderBy('name')->get(),
            'filters' => request()->only('status', 'website'),
        ]);
    }

    public function store(Website $website): RedirectResponse
    {
        $backup = $this->backupService->requestBackup($website, request()->user());

        $message = $backup->status === 'completed'
            ? "Backup created for {$website->name}."
            : ($backup->failure_message ?: "Backup request sent for {$website->name}.");

        return back()->with($backup->status === 'failed' ? 'error' : 'status', $message);
    }

    public function restore(Backup $backup): RedirectResponse
    {
        return back()->with('error', 'Backup restore is intentionally deferred until Phase 2.');
    }

    public function download(Backup $backup)
    {
        abort_unless($backup->file_path, 404);
        abort_unless(Storage::disk($backup->storage_disk)->exists($backup->file_path), 404);

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

    public function destroy(Backup $backup): RedirectResponse
    {
        $this->backupService->delete($backup, request()->user());

        return back()->with('status', 'Backup record deleted.');
    }
}
