package com.ruoyi.web.modules.category.support;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.store.constant.ShopConstants;
import com.ruoyi.web.modules.store.domain.BizMerchantAccount;
import com.ruoyi.web.modules.store.support.SellerShopContextSupport;

/**
 * 解析并校验商家端当前店铺 ID（请求头 X-Shop-Id）
 */
@Component
public class SellerShopContextInterceptor implements HandlerInterceptor
{
    @Autowired
    private SellerShopContextSupport sellerShopContextSupport;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    {
        if (isContextPath(request))
        {
            return true;
        }
        String shopIdHeader = request.getHeader(ShopConstants.HEADER_SHOP_ID);
        if (StringUtils.isEmpty(shopIdHeader))
        {
            return true;
        }
        Long shopId = Long.valueOf(shopIdHeader);
        Long userId = SecurityUtils.getUserId();
        BizMerchantAccount account = sellerShopContextSupport.requireSellerAccount(userId);
        sellerShopContextSupport.assertShopAccessible(account, shopId);
        SellerShopContext.setShopId(shopId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    {
        SellerShopContext.clear();
    }

    private boolean isContextPath(HttpServletRequest request)
    {
        String uri = request.getRequestURI();
        return uri != null && uri.startsWith("/agri/seller/context");
    }
}
