<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * 门店隔离中间件
 * 验证并设置当前用户的门店上下文
 */
class StoreIsolation
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        if (!$user) {
            return response()->json(['code' => 40100, 'message' => '未认证'], 401);
        }

        // 超级管理员可通过 Header 切换门店
        if ($user->is_super && $request->header('X-Store-Id')) {
            $storeId = (int) $request->header('X-Store-Id');
            // 验证门店存在
            if (!\App\Models\Store::where('id', $storeId)->exists()) {
                return response()->json(['code' => 40400, 'message' => '门店不存在'], 404);
            }
        }

        return $next($request);
    }
}
