package com.samsung.interceptor;

import com.samsung.common.util.WebUtil;
import com.samsung.loginout.LoginOutLogService;
import com.samsung.loginout.entity.LoginOut;
import com.samsung.user.UserService;
import com.samsung.user.entity.User;
import com.samsung.user.interceptor.LoginInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Map;

@Log4j2
public class LoginOutLogInterceptor implements LoginInterceptor {

    @Autowired
    private LoginOutLogService loginOutLogService;

    @Autowired
    private UserService userService;

    @Autowired
    private WebUtil webUtil;

    @Override
    public void postLogin(HttpServletRequest request, HttpServletResponse response, User user) {
        LoginOut loginOut = new LoginOut();

        if (StringUtils.isNotEmpty(user.getJwt())) {
            loginOut.setToken(user.getJwt().substring(user.getJwt().lastIndexOf('.') + 1));
        }
        loginOut.setUserId(user.getUserId());
        loginOut.setLoginTime(new Date());
        loginOut.setUseIp(user.getRecentLoginIp());
        loginOut.setReqType("WEB");

        loginOutLogService.insertLogin(loginOut);
    }

    @Override
    public void preLogout(HttpServletRequest request, HttpServletResponse response, User user) {
        LoginOut loginOut = new LoginOut();

        if (StringUtils.isNotEmpty(user.getJwt())) {
            loginOut.setToken(user.getJwt().substring(user.getJwt().lastIndexOf('.') + 1));
        }
        loginOut.setUserId(user.getUserId());
        loginOut.setLoginTime(user.getRecentLoginDatetime());
        loginOut.setLogoutTime(new Date());
        loginOut.setUseIp(webUtil.getClientIp(request));
        loginOut.setReqType("WEB");

        loginOutLogService.updateLogout(loginOut);

        userService.updateUserJwt(Map.of("userId", user.getUserId(), "lastLogoutDate", new Date(), "jwt", ""));
    }
}
