package ru.soune.nocopy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import ru.soune.nocopy.dto.BaseRequest;
import ru.soune.nocopy.dto.BaseResponse;
import ru.soune.nocopy.dto.MessageCode;
import ru.soune.nocopy.dto.file.ActionResponse;
import ru.soune.nocopy.dto.register.ResetPasswordRequest;
import ru.soune.nocopy.dto.register.ResetPasswordResponse;
import ru.soune.nocopy.entity.user.EmailVerificationToken;
import ru.soune.nocopy.entity.user.User;
import ru.soune.nocopy.exception.UserNotFoundException;
import ru.soune.nocopy.repository.EmailVerificationTokenRepository;
import ru.soune.nocopy.repository.UserRepository;
import ru.soune.nocopy.service.mail.EmailService;
import ru.soune.nocopy.util.JwtUtil;

import java.util.Arrays;
import java.util.Map;

@Component
@Slf4j
@RequiredArgsConstructor
public class ResetPasswordHandler implements RequestHandler{

    private final ObjectMapper objectMapper;

    private final EmailService emailService;

    private final UserRepository userRepository;

    private final EmailVerificationTokenRepository emailVerificationTokenRepository;

    private final PasswordEncoder passwordEncoder;

    private final JwtUtil jwtUtil;

    @Override
    public BaseResponse handle(BaseRequest request) throws Exception {
        ResetPasswordRequest resetPasswordRequest = objectMapper.convertValue(request.getMessageBody(),
                ResetPasswordRequest.class);
        String action = resetPasswordRequest.getAction();
        User user = userRepository.findByEmail(resetPasswordRequest.getEmail());

        if (user == null) {
            throw new UserNotFoundException("User not found with email: " + resetPasswordRequest.getEmail());
        }

        String authToken;
        switch (action) {
            case "resetPassword":
                authToken = jwtUtil.generateToken(user.getId(), user.getEmail());

                EmailVerificationToken emailToken = emailService.createEmailVerificationToken(user);

                emailService.sendResetPasswordEmail(user, emailToken.getToken());

                return successResponse(request, authToken, user, MessageCode.SUCCESS.getDescription());
            case "confirmVerification":
                String verifyToken = resetPasswordRequest.getVerifyToken();

                EmailVerificationToken verificationToken =
                        emailVerificationTokenRepository.findByUserIdAndToken(user.getId(), verifyToken);

                if (verificationToken == null) {
                    return new BaseResponse(request.getMsgId(), MessageCode.INVALID_TOKEN.getCode(),
                            MessageCode.INVALID_TOKEN.getDescription(), Map.of("verifyToken", verifyToken));
                }

                authToken = jwtUtil.generateToken(user.getId(), user.getEmail());

                user.setPassword(passwordEncoder.encode(resetPasswordRequest.getPassword()));
                user.setActive(true);

                emailVerificationTokenRepository.delete(verificationToken);

                User saveUser = userRepository.save(user);

                return successResponse(request, authToken, saveUser, MessageCode.SUCCESS.getDescription());
            default:
                ActionResponse response = ActionResponse.builder()
                        .action(action)
                        .availableActions(Arrays.asList("confirmVerification", "resetPassword"))
                        .build();

                return new BaseResponse(request.getMsgId(), MessageCode.INVALID_ACTION.getCode(),
                        "Invalid action: " + action, response);

        }
    }

    private BaseResponse successResponse(BaseRequest request, String authToken, User user, String message) {
        ResetPasswordResponse resetPasswordResponse = new ResetPasswordResponse();
        resetPasswordResponse.setAuthToken(authToken);
        resetPasswordResponse.setUserId(user.getId());

        return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(), message, resetPasswordResponse);
    }
}