package com.eactive.testmaster.user.service;

import com.eactive.testmaster.common.entity.EnabledStatus;
import com.eactive.testmaster.common.exception.UserNotFoundException;
import com.eactive.testmaster.common.util.EncryptionUtil;
import com.eactive.testmaster.login.entity.Token;
import com.eactive.testmaster.login.service.TokenService;
import com.eactive.testmaster.user.entity.StaffUser;
import com.eactive.testmaster.user.entity.User;
import com.eactive.testmaster.user.repository.StaffUserRepository;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

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

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


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

    private final StaffUserRepository staffUserRepository;

    private EncryptionUtil encryptionUtil;

    private final TokenService tokenService;

    public UserService(StaffUserRepository staffUserRepository, EncryptionUtil encryptionUtil, TokenService tokenService) {
        this.staffUserRepository = staffUserRepository;
        this.encryptionUtil = encryptionUtil;
        this.tokenService = tokenService;
    }

    @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 requestPasswordReset(String email) {

        Token token = tokenService.createToken(email);
        Map<String, Object> params = new HashMap<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = token.getExpiresAt().format(formatter);

        params.put("userId", email);
        params.put("token", token.getTokenValue());
        params.put("expiresAt", formattedDateTime);

        logger.info("requestPasswordReset::params= {}", params);
    }

    public void resetPassword(String email, String newPassword) {
        User user = findByUserId(email);
        updatePassword(user, newPassword);
    }

    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;
    }
}
