package com.dbnt.kcscbackend.config.security;

import com.dbnt.kcscbackend.auth.entity.UserInfo;
import com.dbnt.kcscbackend.config.jwt.EgovJwtTokenUtil;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

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

@RequiredArgsConstructor
@Configuration
public class CustomUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

  private final EgovJwtTokenUtil jwtTokenUtil;
  private RequestCache requestCache = new HttpSessionRequestCache();

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                      Authentication authentication) throws ServletException, IOException {

    SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest != null) {
      requestCache.removeRequest(request, response);
      clearAuthenticationAttributes(request);
    }

    UserInfo securityUser = null;
    if (SecurityContextHolder.getContext().getAuthentication() != null) {
      Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      if (principal instanceof UserDetails) {
        securityUser = (UserInfo) principal;
      }
    }

    // application/json(ajax) 요청일 경우 아래의 처리!
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    MediaType jsonMimeType = MediaType.APPLICATION_JSON;

    String accessToken = jwtTokenUtil.generateAccessToken(securityUser, request.getRemoteAddr());
    String refreshToken = jwtTokenUtil.generateRefreshTokenToken(securityUser, request.getRemoteAddr());
    HashMap<String, Object> resultMap = new HashMap<>();
    resultMap.put("resultCode", "200");
    resultMap.put("accessToken", accessToken);
    resultMap.put("refreshToken", refreshToken);
//    response.addHeader("Authorization", "BEARER "+accessToken);
//    Cookie refreshTokenCookie = new Cookie("refreshToken", refreshToken);
//    response.addCookie(refreshTokenCookie);
    if (jsonConverter.canWrite(resultMap.getClass(), jsonMimeType)) {
      jsonConverter.write(resultMap, jsonMimeType, new ServletServerHttpResponse(response));
    }
  }

  public void setRequestCache(RequestCache requestCache) {
    this.requestCache = requestCache;
  }
}
