package org.qinan.safetyeval.adapter.config;

import lombok.extern.slf4j.Slf4j;
import org.qinan.safetyeval.domain.exception.BizException;
import org.qinan.safetyeval.domain.exception.ErrorCode;
import org.qinan.safetyeval.infrastructure.adapter.auth.AuthUserContextAdapter;
import org.qinan.safetyeval.infrastructure.adapter.auth.AuthUserInfo;
import org.qinan.safetyeval.infrastructure.dataobject.AccountDO;
import org.qinan.safetyeval.infrastructure.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
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
@Slf4j
public class GbsUserSyncInterceptor implements WebMvcConfigurer {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                if (!(handler instanceof HandlerMethod)) {
                    return true;
                }
                AuthUserInfo currentUser = AuthUserContextAdapter.getCurrentUser();
                if (currentUser == null) {
                    throw new BizException(ErrorCode.GBS_USER_ERROR);
                }
                AccountDO accountDO = accountMapper.selectById(currentUser.getUserId());
                if (accountDO == null) {
                    // 用户没有gbs信息,自动填充一条数据类型默认监管端
                    AccountDO accountSave = new AccountDO();
                    accountSave.setId(currentUser.getUserId());
                    accountSave.setUserName(currentUser.getUserName());
                    accountSave.setAccount(currentUser.getAccount());
                    accountSave.setPhone(currentUser.getMobile());
                    accountSave.setTenantId(currentUser.getTenantId());
                    accountSave.setType(2);
                    accountMapper.insert(accountSave);
                    log.info("用户{}同步gbs信息成功", currentUser.getUserName());
                }
                return true;
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                        Object handler, Exception exception) {

            }
        }).addPathPatterns("/**").order(2);
    }
}
