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.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.logout.LogoutSuccessHandler;

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;

@Configuration
@RequiredArgsConstructor
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
  private final EgovJwtTokenUtil jwtTokenUtil;
  private final AdminLogsService adminLogsService;

  @Override
  public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    Cookie refreshToken = new Cookie("refreshToken", null);
    refreshToken.setMaxAge(0);
    refreshToken.setPath("/");
    response.addCookie(refreshToken);

    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    MediaType jsonMimeType = MediaType.APPLICATION_JSON;

    HashMap<String, Object> resultMap = new HashMap<String, Object>();
    resultMap.put("resultCode", "200");

    //로그아웃 이력 생성
    String accessToken = request.getHeader("Authorization");
    adminLogsService.insertLoginLog(jwtTokenUtil.getUserIdFromToken(accessToken), ClientUtils.getRemoteIP(request), accessToken, "N", ClientUtils.getWebType(request));

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