package com.njcn.product.event.transientes.security;

import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.product.event.transientes.utils.JwtUtil;
import com.njcn.product.event.config.RedisUtil;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

@RestController
@Slf4j
@RequiredArgsConstructor
public class AuthController extends BaseController {

    private final String eventRedisKey = "event_smart_";


    private final AuthenticationManager authenticationManager;


    private final JwtUtil jwtUtil;

    private final RedisUtil redisUtil;


    @PostMapping("/cn_authenticate")
    @ApiOperation("登录认证")
    public HttpResult<AuthResponse> createAuthenticationToken(@RequestBody @Validated AuthRequest authRequest) {
        String methodDescribe = getMethodDescribe("createAuthenticationToken");
        //log.info("Authentication request - username: {}, password: {}",authRequest.getUsername(),authRequest.getPassword());
        try {
            boolean hasFlag;
            String pass;
            //针对系统推送的认证特殊处理
            if ("system_event".equals(authRequest.getUsername())) {
                pass = authRequest.getPassword();
            } else if ("cn_test_a".equals(authRequest.getUsername())) {
                pass = authRequest.getPassword();
            } else {
                hasFlag = redisUtil.hasKey(eventRedisKey + authRequest.getUsername());
                if (hasFlag) {
                    pass = redisUtil.getRawValue(eventRedisKey + authRequest.getUsername());
                } else {
                    return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
                }
            }
            // 执行认证，内部会调用 UserDetailsService 加载用户信息
            Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authRequest.getUsername(), pass));

            // 将认证信息存入 SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 直接从 Authentication 对象中获取已加载的 UserDetails，避免重复查询
            MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();

            // 获取用户部门（假设 CustomUserDetails 包含部门信息）
            String department = userDetails.getDeptId();

            final String jwt = jwtUtil.generateToken(userDetails);

            AuthResponse authResponse = new AuthResponse();
            authResponse.setToken(jwt);
            authResponse.setDeptId(department);
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, authResponse, methodDescribe);

        } catch (Exception e) {
            e.printStackTrace();
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
        }
    }
}

// 认证请求类
class AuthRequest {

    @NotBlank(message = "用户名不可为空")
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
