<?php

namespace App\Http\Middleware;

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

class RestaurantAccessMiddleware
{
    /**
     * Handle an incoming request.
     * Ensure users can only access their restaurant's data
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (!auth()->check()) {
            return response()->json(['message' => 'Unauthenticated'], 401);
        }

        $user = auth()->user();

        // Admin users have access to all restaurants
        if ($user->isAdmin()) {
            return $next($request);
        }

        // Restaurant owners can only access their restaurant
        if ($user->isRestaurantOwner()) {
            if (!$user->restaurant_id) {
                return response()->json(['message' => 'Restaurant owner must be assigned to a restaurant'], 403);
            }
            // Set restaurant context for the request
            $request->merge(['restaurant_id' => $user->restaurant_id]);
            return $next($request);
        }

        // Branch managers can only access their branch's restaurant
        if ($user->isBranchManager()) {
            if (!$user->branch_id) {
                return response()->json(['message' => 'Branch manager must be assigned to a branch'], 403);
            }
            $branch = $user->branch;
            if (!$branch || !$branch->restaurant_id) {
                return response()->json(['message' => 'Branch must be assigned to a restaurant'], 403);
            }
            $request->merge(['restaurant_id' => $branch->restaurant_id, 'branch_id' => $user->branch_id]);
            return $next($request);
        }

        // Staff users can only access their branch's restaurant
        if ($user->branch_id) {
            $branch = $user->branch;
            if ($branch && $branch->restaurant_id) {
                $request->merge(['restaurant_id' => $branch->restaurant_id, 'branch_id' => $user->branch_id]);
            }
        }

        return $next($request);
    }
}
