<?php

namespace App\Http\Middleware;

use App\Services\ResponseService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckPermission
{
    protected ResponseService $responseService;

    public function __construct(ResponseService $responseService)
    {
        $this->responseService = $responseService;
    }

    public function handle(Request $request, Closure $next, string $permission): Response
    {
        $user = $request->user();

        if (!$user) {
            return $this->responseService->unauthorized('Authentication required');
        }

        if ($user->hasRole('super-admin')) {
            return $next($request);
        }

        if (!$user->hasPermissionTo($permission)) {
            return $this->responseService->forbidden("You don't have permission to perform this action");
        }

        return $next($request);
    }
}
