package com.eactive.httpmockserver.user.service;

import com.eactive.httpmockserver.common.entity.EnabledStatus;
import com.eactive.httpmockserver.common.exception.UserNotFoundException;
import com.eactive.httpmockserver.common.util.EncryptionUtil;
import com.eactive.httpmockserver.user.entity.StaffUser;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.repository.StaffUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
//@Transactional(propagation = Propagation.NESTED)
public class UserService implements UserDetailsService {

    public static final String USER_NOT_FOUND_MESSAGE = "사용자 정보가 존재하지 않습니다.";

    @Autowired
    StaffUserRepository staffUserRepository;

    @Autowired
    private EncryptionUtil encryptionUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            return findByUserId(username);
        } catch (UserNotFoundException e) {
            throw new UsernameNotFoundException(e.getMessage());
        }
    }

    public User findByUserId(String userId) {
        return staffUserRepository.findByUserId(userId).orElseThrow(() -> new UserNotFoundException(USER_NOT_FOUND_MESSAGE));
    }

    public String updateUserPassword(String esntlId, String oldPassword, String newPassword, String newPassword2) {
        User user = staffUserRepository.findById(esntlId).orElseThrow(() -> new UserNotFoundException(USER_NOT_FOUND_MESSAGE));
        String encryptedOldPass = encryptionUtil.encryptPassword(oldPassword, user.getUserId());
        String resultMsg = null;

        if (encryptedOldPass.equals(user.getPassword())) {
            if (newPassword.equals(newPassword2)) {
                updatePassword(user, newPassword);
                resultMsg = "success.common.update";
            } else {
                resultMsg = "fail.user.passwordUpdate2";
            }
        } else {
            resultMsg = "fail.user.passwordUpdate1";
        }

        return resultMsg;
    }

    public void updatePassword(User user, String newPassword) {
        user.setPassword(encryptionUtil.encryptPassword(newPassword, user.getUserId()));
        user.setLockAt(EnabledStatus.N);
        user.setLockCnt(0);
        user.setLastPasswordChangeDate(LocalDateTime.now());
        staffUserRepository.save((StaffUser) user);
    }

    public void updateUser(User user) {
        staffUserRepository.save((StaffUser) user);
    }
    public StaffUser findByEsntlId(String esntlId) {
        return staffUserRepository.findById(esntlId).orElseThrow(() -> new UserNotFoundException(USER_NOT_FOUND_MESSAGE));
    }

    public boolean isInitialized(){
        return staffUserRepository.count() > 0;
    }
}
