package com.malk.pro.tenant;

import com.alibaba.fastjson.JSON;
import com.malk.server.common.McR;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * 租户解析拦截器（capability: multi-tenant-runtime）
 *
 * <ul>
 *   <li>preHandle：读 {@code X-Tenant-Id} → 查注册表 → {@link TenantContext#set}，并写 MDC {@code tenantId}</li>
 *   <li>afterCompletion：清 TenantContext + MDC</li>
 *   <li>缺失 → 401 {@code TENANT_REQUIRED}；不存在 → 403 {@code TENANT_NOT_FOUND}</li>
 * </ul>
 */
@Component
public class TenantInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = LoggerFactory.getLogger("point");
    public static final String HEADER = "X-Tenant-Id";
    public static final String MDC_KEY = "tenantId";

    @Autowired
    private TenantRegistryService registry;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tenantId = request.getHeader(HEADER);
        if (tenantId == null || tenantId.isEmpty()) {
            write(response, 401, "TENANT_REQUIRED");
            log.warn("[Tenant] header missing path={}", request.getServletPath());
            return false;
        }
        TenantProfile profile = registry.get(tenantId);
        if (profile == null || !profile.isEnabled()) {
            write(response, 403, "TENANT_NOT_FOUND");
            log.warn("[Tenant] not found or disabled tenantId={} path={}", tenantId, request.getServletPath());
            return false;
        }
        TenantContext.set(profile);
        MDC.put(MDC_KEY, tenantId);
        return true;
    }

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

    private static void write(HttpServletResponse resp, int status, String code) throws java.io.IOException {
        resp.setStatus(status);
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        McR r = McR.error(code, code);
        resp.getOutputStream().write(JSON.toJSONString(r).getBytes(StandardCharsets.UTF_8));
    }
}
