<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

/**
 * Desktop sync endpoints accept a client-supplied `shop_id` for query scoping,
 * but the client cannot be trusted to send its own shop_id honestly (or correctly).
 * This forces every sync request to only ever operate on the shop_id that the
 * authenticated Sanctum token (employee) actually belongs to, so one employee's
 * desktop app can never read or write another shop's data.
 */
class EnsureShopIdMatchesAuthenticatedUser
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (!$user || empty($user->shop_id)) {
            return response()->json([
                'success' => false,
                'message' => 'No shop assigned to this account.',
            ], 403);
        }

        $requestedShopId = $request->input('shop_id');

        if ($requestedShopId !== null && (string) $requestedShopId !== (string) $user->shop_id) {
            Log::channel('security')->warning('Sync request shop_id mismatch blocked', [
                'user_id' => $user->id,
                'user_shop_id' => $user->shop_id,
                'requested_shop_id' => $requestedShopId,
                'endpoint' => $request->path(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'You are not authorized to access this shop\'s data.',
            ], 403);
        }

        // Force the authenticated user's own shop_id regardless of what was sent,
        // so downstream controllers can never be tricked by a forged/stale value.
        $request->merge(['shop_id' => $user->shop_id]);

        return $next($request);
    }
}
