package org.lingniu.idp.security.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.lingniu.idp.constant.Constants;
import org.lingniu.idp.manager.AsyncManager;
import org.lingniu.idp.manager.factory.AsyncFactory;
import org.lingniu.idp.model.dto.LoginUser;
import org.lingniu.idp.model.vo.TokenInfo;
import org.lingniu.idp.service.core.login.IdpTokenService;
import org.lingniu.idp.utils.MessageUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final IdpTokenService idpTokenService;

    public LoginSuccessHandler(IdpTokenService idpTokenService) {
        this.idpTokenService = idpTokenService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 生成token
        TokenInfo token = idpTokenService.createToken(request, loginUser);
        // 保存token
        idpTokenService.storeTokenInfo(token);
        // 将短token放入响应头
        idpTokenService.setAccessTokenHeader(response,token.getAccessTokenInfo().getTokenValue());
        // 设置Refresh Token到HttpOnly Cookie
        idpTokenService.setRefreshTokenCookie(response, token);
        // 记录审计日志
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginUser.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 保存日志
        idpTokenService.recordLoginInfo(loginUser.getUserId());
    }


}
