package com.dbnt.kcscbackend.config.security;

import com.dbnt.kcscbackend.admin.logs.service.AdminLogsService;
import com.dbnt.kcscbackend.auth.entity.UserInfo;
import com.dbnt.kcscbackend.config.common.ResponseCode;
import com.dbnt.kcscbackend.config.egov.EgovProperties;
import com.dbnt.kcscbackend.config.jwt.EgovJwtTokenUtil;
import com.dbnt.kcscbackend.config.util.ClientUtils;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


@Configuration
@RequiredArgsConstructor
public class CustomUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

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

  private static final List<String> adminIpList = Arrays.asList(EgovProperties.getProperty("Globals.admin.allow-ip").split(","));

  @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;
      }
    }
    String accessIp = ClientUtils.getRemoteIP(request);

    // application/json(ajax) 요청일 경우 아래의 처리!
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    MediaType jsonMimeType = MediaType.APPLICATION_JSON;
    HashMap<String, Object> resultMap = new HashMap<>();

    /*
    // 관리자 계정 로그인 제한 if문
    if(securityUser.getUserId().equals("admin") && !adminIpList.contains(accessIp)){
      resultMap.put("resultCode", ResponseCode.FAILED.getCode());
      resultMap.put("resultMessage", "관리자 계정은 지정된 아이피에서만 접속할 수 있습니다.\n필요한 경우 관리자에게 요청하십시오.\n접속자 아이피: "+ClientUtils.getRemoteIP(request));
    }else{
      String accessToken = jwtTokenUtil.generateAccessToken(securityUser, request.getRemoteAddr());
      String refreshToken = jwtTokenUtil.generateRefreshTokenToken(securityUser, request.getRemoteAddr());
      resultMap.put("resultCode", ResponseCode.SUCCESS.getCode());
      resultMap.put("accessToken", accessToken);
      resultMap.put("refreshToken", refreshToken);
      //로그인 로그 기록
      adminLogsService.insertLoginLog(securityUser.getUserId(), accessIp, accessToken, "Y", ClientUtils.getWebType(request));
    }*/

    // 관리자 로그인 제한 해제 위 if문 주석처리 할 것.
    String accessToken = jwtTokenUtil.generateAccessToken(securityUser, request.getRemoteAddr());
    String refreshToken = jwtTokenUtil.generateRefreshTokenToken(securityUser, request.getRemoteAddr());
    resultMap.put("resultCode", ResponseCode.SUCCESS.getCode());
    resultMap.put("accessToken", accessToken);
    resultMap.put("refreshToken", refreshToken);
    adminLogsService.insertLoginLog(securityUser.getUserId(), accessIp, accessToken, "Y", ClientUtils.getWebType(request));


    if (jsonConverter.canWrite(resultMap.getClass(), jsonMimeType)) {
      jsonConverter.write(resultMap, jsonMimeType, new ServletServerHttpResponse(response));
    }
  }

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