package org.lingniu.sdk.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.lingniu.sdk.model.base.CommonResult;
import org.lingniu.sdk.model.token.TokenInfo;
import org.lingniu.sdk.model.user.UserInfo;
import org.lingniu.sdk.service.TokenService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final TokenService tokenService;
    private final ObjectMapper objectMapper;

    public LoginSuccessHandler(TokenService tokenService, ObjectMapper objectMapper) {
        this.tokenService = tokenService;
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        OAuth2AuthenticationToken oAuth2AuthenticationToken = (OAuth2AuthenticationToken)authentication;
        DefaultOidcUser principal = (DefaultOidcUser)oAuth2AuthenticationToken.getPrincipal();
        Map<String, Object> claims = principal.getUserInfo().getClaims();
        String clientRegistrationId = oAuth2AuthenticationToken.getAuthorizedClientRegistrationId();
        String s = objectMapper.writeValueAsString(claims);
        // 生成token
        TokenInfo token = tokenService.createToken(principal.getName());
        token.getAccessTokenInfo().setAdditionalInfo(s);
        token.getAccessTokenInfo().setClientRegistrationId(clientRegistrationId);
        token.getRefreshTokenInfo().setClientRegistrationId(clientRegistrationId);
        // 保存token
        tokenService.storeTokenInfo(token);
        // 将短token放入响应头
        tokenService.setAccessTokenHeader(response,token.getAccessTokenInfo().getTokenValue());
        // 设置Refresh Token到HttpOnly Cookie
        tokenService.setRefreshTokenCookie(response, token);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.OK.value());
        objectMapper.writeValue(response.getWriter(), CommonResult.success(CommonResult.success(claims)));
    }


}
