package org.qinan.safetyeval.adapter.config;

import org.qinan.safetyeval.infrastructure.adapter.ThreadLocalUserInfoAdapter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 本地联调：为免鉴权的企业信息接口注入默认用户上下文，供 MyMetaObjectHandler 填充 org_id / tenant_id。
 */
@Configuration
public class LocalDevUserContextConfig implements WebMvcConfigurer {

    @Value("${safety-eval.public-api.org-id:0}")
    private Long defaultOrgId;

    private static final String[] LOCAL_DEV_PATHS = {
            "/org-info/**",
            "/org-department/**",
            "/org-position/**",
            "/org-qualification/**",
            "/org-personnel/**",
            "/org-personnel-cert/**",
            "/org-personnel-change/**",
            "/org-resign-apply/**",
            "/org-equipment/**",
            "/qual-filing/**",
            "/qual-filing-change/**",
            "/qual-filing-change-detail/**",
            "/qual-filing-commitment/**",
            "/qual-filing-equipment/**",
            "/qual-filing-material/**",
            "/qual-filing-personnel/**",
            "/qual-filing-personnel-cert/**",
    };

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                String orgInfoId = request.getHeader("orgInfoId");
                if (StringUtils.hasText(orgInfoId)) {
                    ThreadLocalUserInfoAdapter.set(Long.valueOf(orgInfoId));
                } else if (defaultOrgId != null && defaultOrgId > 0) {
                    ThreadLocalUserInfoAdapter.set(defaultOrgId);
                }
                return true;
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                        Object handler, Exception exception) {
                ThreadLocalUserInfoAdapter.clear();
            }
        }).addPathPatterns(LOCAL_DEV_PATHS).excludePathPatterns("/**/getInfo/**");
    }
}
