package com.eactive.httpmockserver.config;


import com.eactive.httpmockserver.common.util.EncryptionUtil;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class PortalAuthenticationManager implements AuthenticationManager {

    @Autowired
    private UserService userService;

    @Autowired
    private EncryptionUtil encryptionUtil;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String username = token.getName();
        String password = token.getCredentials().toString();
        String encryptPassword = encryptionUtil.encryptPassword(password, username);

        UserDetails user = userService.loadUserByUsername(username);

        if (!user.isEnabled()) {
            throw new DisabledException("계정이 " + ((User) user).getStatus().getDescription() + "상태입니다. 관리자에게 문의하세요.");
        }

        if (!user.isAccountNonLocked()) {
            throw new LockedException("계정이 잠겨있습니다. 관리자에게 문의하세요.");
        }

        if (user.getPassword().equals(encryptPassword)) {

            UsernamePasswordAuthenticationToken authorityToken = new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
            authorityToken.setDetails(user);
            SecurityContextHolder.getContext().setAuthentication(authorityToken);
            return authorityToken;
        }

        throw new BadCredentialsException("아이디 또는 비밀번호가 일치하지 않습니다.");
    }

}
