<?php

namespace App\Modules\Core\Middleware;

use App\Http\Responses\ApiResponse;
use App\Models\User;
use App\Modules\Tenant\Models\Company;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureCompanyAccess
{
    /**
     * @param Closure(Request): Response $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $companyId = $request->header('X-Company-ID');

        if (! $companyId) {
            return ApiResponse::error('X-Company-ID header is required', 422);
        }

        $user = $request->user();

        if (! $user instanceof User) {
            return ApiResponse::error('Company access denied', 403);
        }

        $company = $user->companies()->whereKey($companyId)->first();

        if (! $company instanceof Company) {
            return ApiResponse::error('Company access denied', 403);
        }

        app()->instance('currentCompany', $company);
        $request->attributes->set('currentCompany', $company);

        return $next($request);
    }
}
