package ru.soune.nocopy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import ru.soune.nocopy.dto.*;
import ru.soune.nocopy.dto.register.LoginAnswer;
import ru.soune.nocopy.dto.register.LoginRequest;
import ru.soune.nocopy.entity.user.AuthToken;
import ru.soune.nocopy.entity.user.User;
import ru.soune.nocopy.exception.NotValidFieldException;
import ru.soune.nocopy.repository.UserRepository;
import ru.soune.nocopy.service.register.AuthService;

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

@Component
@RequiredArgsConstructor
public class LoginRequestHandler implements RequestHandler {

    private final UserRepository userRepository;

    private final AuthService authService;

    private final ObjectMapper objectMapper;

    @Override
    public BaseResponse handle(BaseRequest request) {
        LoginRequest loginRequest = objectMapper.convertValue(request.getMessageBody(), LoginRequest.class);
        User user = userRepository.findByEmail(loginRequest.getEmail());

        if (user == null) {
            LoginAnswer loginAnswer = new LoginAnswer();
            loginAnswer.setFieldErrors(Arrays.asList(Map.of("email", loginRequest.getEmail())));

            throw new NotValidFieldException("User with email not found: " + loginRequest.getEmail(),
                    new BaseResponse(request.getMsgId(), MessageCode.AUTH_EMAIL_NOT_FOUND.getCode(),
                            MessageCode.AUTH_EMAIL_NOT_FOUND.getDescription(), loginAnswer));
        }

        if (!user.isActive() && !user.isEmailVerified()) {
            LoginAnswer loginAnswer = new LoginAnswer();

            loginAnswer.setFieldErrors(Arrays.asList(Map.of(
                    "verified", String.valueOf(user.isEmailVerified()),
                    "isActive", String.valueOf(user.isActive()))));

            return new BaseResponse(request.getMsgId(), MessageCode.USER_NOT_VERIFIED.getCode(),
                    MessageCode.USER_NOT_VERIFIED.getDescription(), loginAnswer);
        }

        if (!user.canLogin()) {
            LoginAnswer loginAnswer = new LoginAnswer();

            loginAnswer.setFieldErrors(Arrays.asList(Map.of(
                    "login_permission", "not found")));

            return new BaseResponse(request.getMsgId(), MessageCode.PERMISSION_NOT_FOUND.getCode(),
                    MessageCode.PERMISSION_NOT_FOUND.getDescription(), loginAnswer);
        }

        AuthToken authToken = authService.login(loginRequest);
        String token = authToken.getToken();

        LoginAnswer loginAnswer = new LoginAnswer();
        loginAnswer.setToken(token);

        authService.useUserAuthToken(token);

        return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(),
                MessageCode.SUCCESS.getDescription(), loginAnswer);
    }
}
