package com.eactive.httpmockserver.config;

import com.eactive.httpmockserver.common.entity.EnabledStatus;
import com.eactive.httpmockserver.common.exception.UserNotFoundException;
import com.eactive.httpmockserver.login.controller.LoginController;
import com.eactive.httpmockserver.user.entity.StaffUser;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.repository.StaffUserRepository;
import com.eactive.httpmockserver.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Service
@Transactional
public class PortalAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private static final Logger logger = LoggerFactory.getLogger(PortalAuthenticationFailureHandler.class);

    UserService userService;

    StaffUserRepository staffUserRepository;

    public PortalAuthenticationFailureHandler(UserService userService, StaffUserRepository staffUserRepository) {
        this.userService = userService;
        this.staffUserRepository = staffUserRepository;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, noRollbackFor = {AuthenticationException.class, UserNotFoundException.class})
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {

        String username = request.getParameter("id");
        try {
            User user = userService.findByUserId(username);
            if (user != null) {
                user.setLockCnt(user.getLockCnt() + 1);
                if (user.getLockCnt() >= 5) {
                    user.setLockAt(EnabledStatus.Y);
                }

                staffUserRepository.save((StaffUser) user);
            }
        } catch (UserNotFoundException e) {
            logger.error("{} login try {}", username, e.getMessage());
        }

        request.getSession().setAttribute(LoginController.LOGIN_MESSAGE, exception.getLocalizedMessage());
        String contextPath = request.getContextPath();
        response.sendRedirect(contextPath + "/login");
    }
}
