<?php

namespace App\Http\Controllers;

use App\Models\BackupLog;
use App\Services\BackupService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class BackupController extends Controller
{
    public function __construct(protected BackupService $backups)
    {
        $this->middleware('permission:backups.view')->only(['index']);
        $this->middleware('permission:backups.create')->only(['store']);
        $this->middleware('permission:backups.delete')->only(['destroy']);
    }

    public function index()
    {
        $backups = BackupLog::query()->with('creator')->latest()->paginate(20);

        return view('system.backups', compact('backups'));
    }

    public function store(Request $request)
    {
        $this->backups->create($request->user());

        return back()->with('success', __('messages.backup_created'));
    }

    public function download(BackupLog $backup): StreamedResponse
    {
        abort_unless(auth()->user()->can('backups.view') || auth()->user()->hasRole('Administrator'), 403);
        abort_unless(is_file($backup->path), 404);

        return response()->download($backup->path, $backup->filename);
    }

    public function destroy(BackupLog $backup)
    {
        $this->backups->delete($backup);

        return back()->with('success', __('messages.updated'));
    }
}
