<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;

class BackupDownloadMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if user is authenticated
        if (!Auth::check()) {
            abort(401, 'Unauthenticated.');
        }

        // Check if user has admin role
        if (Auth::user()->role?->name !== 'admin') {
            abort(403, 'Unauthorized.');
        }

        // Start session without cookie-related middleware
        if (!$request->hasSession()) {
            $request->session()->start();
        }

        return $next($request);
    }
}
