package com.xingxi.api.configuration.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xingxi.common.core.domain.entity.SysUser;
import com.xingxi.api.common.ResponseDTO;
import com.xingxi.api.common.AccessTokenDTO;
import com.xingxi.api.common.JWTUtils;
import com.xingxi.api.data.domain.UserProfileDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
class WxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.debug("WxAuthenticationSuccessHandler.onAuthenticationSuccess()...");

        SysUser sysUser = (SysUser) authentication.getPrincipal();

        UserProfileDTO userProfileDTO = new UserProfileDTO();
        userProfileDTO.setUserType(sysUser.getUserType());
        userProfileDTO.setUserId(sysUser.getUserId() + "");
        userProfileDTO.setPhoneNumber(sysUser.getPhonenumber());
        userProfileDTO.setNickName(sysUser.getUserName());
        userProfileDTO.setAvatarUrl(sysUser.getAvatar());
        userProfileDTO.setGender(sysUser.getSex());

        String accessToken = JWTUtils.generateJwtString(sysUser.getWxOpenId(), sysUser.getLoginDate());
        String requestId = (String) request.getAttribute("X-REQUEST-ID");

        ResponseDTO<Map<String, Object>> responseDTO = new ResponseDTO<>(200);
        responseDTO.setRequestId(requestId);
        responseDTO.setData(new HashMap<String, Object>(){{
            put("userProfileDTO", userProfileDTO);
            put("accessTokenDTO", new AccessTokenDTO(accessToken, 14400L));
        }});

        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(responseDTO));

    }
}
