<?php

namespace App\Http\Middleware;

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

class EnsureBranchContext
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        $branchId = $request->header('X-Branch-Id');

        if ($user === null) {
            return response()->json(['message' => 'Unauthenticated.'], Response::HTTP_UNAUTHORIZED);
        }

        if ($branchId === null || ! ctype_digit((string) $branchId)) {
            return response()->json([
                'message' => 'A valid X-Branch-Id header is required.',
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $branchId = (int) $branchId;

        if (! $user->canAccessBranch($branchId)) {
            return response()->json([
                'message' => 'You are not allowed to access this branch.',
            ], Response::HTTP_FORBIDDEN);
        }

        $request->attributes->set('company_id', $user->company_id);
        $request->attributes->set('branch_id', $branchId);

        return $next($request);
    }
}
