package com.style24.scm.support.security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.style24.scm.biz.service.TssLoginService;
import com.style24.scm.support.env.TssConstants;
import com.style24.scm.support.security.TssLoginDetails;
import com.style24.scm.support.security.session.TssSession;

import lombok.extern.slf4j.Slf4j;

/**
 * 로그인 성공 시 호출되는 Handler
 * 
 * @author gagamel
 * @since 2020. 10. 19
 */
@Component
@Slf4j
public class TssLoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private TssLoginService loginService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		// 로그인 상세 정보
		TssLoginDetails loginDetails = (TssLoginDetails)authentication.getDetails();

		Integer userNo = loginDetails.getLoginInfo().getUserNo();
		log.info("userNo: {}", userNo);

		// 로그인 성공 시 로그인실패수가 0보다 크면 로그인실패수 reset
		int failCnt = loginService.getLoginFailCount(userNo);
		if (failCnt > 0) {
			loginService.createLoginFail(userNo, "N");
		}

		// 로그인 메뉴 목록
		loginDetails.setLoginMenuList(loginService.getLoginMenuList(userNo));

		// 최종로그인일시 Update
		loginService.updateLastLoginDate(userNo);

		// 로그인이력 남기기
		loginService.createLoginHistory(userNo);

		// 세션 생성
		this.createSession(request, loginDetails);

		response.sendRedirect("/");
	}

	/**
	 * Session 생성
	 * 
	 * @param request - HttpServletRequest
	 * @param loginDetails - 로그인 상세 정보
	 */
	private void createSession(HttpServletRequest request, TssLoginDetails loginDetails) {
		TssSession.getNewSess(request, -1);
		TssSession.setAttribute(request, loginDetails);

		// 입점업체이면서
		if ("G001_B000".equals(loginDetails.getLoginInfo().getRoleCd())) {
			String headerAuthId = request.getHeader("x-auth-id");	// 샵링커: shoplinker, 사방넷: sabangnet, EC모니터: ecmonitor
			String headerAuthKey = request.getHeader("x-auth-key");	// LOWER(FN_ENC_AES(위의 headerAuthId 값))
			log.info("x-auth-id: {}, x-auth-key: {}", headerAuthId, headerAuthKey);

			// Header에 인증ID와 인증키가 있으면
			if (StringUtils.isNotBlank(headerAuthId) && StringUtils.isNotBlank(headerAuthKey)) {
				String authKey = "";
				if (headerAuthId.equals(TssConstants.SellerAuthKey.SHOPLINKER.name().toLowerCase())) {
					authKey = TssConstants.SellerAuthKey.SHOPLINKER.value();
				} else if (headerAuthId.equals(TssConstants.SellerAuthKey.SABANGNET.name().toLowerCase())) {
					authKey = TssConstants.SellerAuthKey.SABANGNET.value();
				} else if (headerAuthId.equals(TssConstants.SellerAuthKey.ECMONITOR.name().toLowerCase())) {
					authKey = TssConstants.SellerAuthKey.ECMONITOR.value();
				}

				// 입점업체의 인증키와 Header의 인증키가 같으면 2factor인증 skip을 위한 2factor인증 세션을 true로 설정
				if (authKey.equals(headerAuthKey)) {
					log.info("x-auth-key is equal!!!");
					TssSession.setAttribute("isTfcertify", "true");
				}
			}
		}
	}

}
