<?php

namespace App\Modules\Core\Middleware;

use App\Http\Responses\ApiResponse;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureCompanyManager
{
    /**
     * @param Closure(Request): Response $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $company = $request->attributes->get('currentCompany');

        if (! $company) {
            return ApiResponse::error('Company context is required', 422);
        }

        $role = $company->pivot?->role;

        if (! in_array($role, ['owner', 'admin'], true)) {
            return ApiResponse::error('Company manager access required', 403);
        }

        return $next($request);
    }
}
