<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ApiCheckAbility
{
    /**
     * Handle an incoming request.
     *
     * @param  string  $ability
     */
    public function handle(Request $request, Closure $next, string $ability): Response
    {
        $apiToken = $request->attributes->get('api_token');

        if (!$apiToken) {
            return response()->json([
                'success' => false,
                'error' => [
                    'code' => 'UNAUTHORIZED',
                    'message' => 'Authentication required.',
                ]
            ], 401);
        }

        // Verifică dacă token has Necesar ability
        if (!$apiToken->can($ability)) {
            return response()->json([
                'success' => false,
                'error' => [
                    'code' => 'FORBIDDEN',
                    'message' => 'You do not have permission to perform this action.',
                    'details' => [
                        'required_ability' => $ability,
                    ]
                ]
            ], 403);
        }

        return $next($request);
    }
}
