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.LogOutAnswer;
import ru.soune.nocopy.dto.register.LogoutRequest;
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.AuthTokenRepository;
import ru.soune.nocopy.repository.UserRepository;
import ru.soune.nocopy.service.register.AuthService;

import java.util.Objects;
import java.util.Optional;

@Component
@RequiredArgsConstructor
public class LogoutRequestHandler implements RequestHandler {

    private final AuthService authService;

    private final AuthTokenRepository authTokenRepository;

    private final ObjectMapper objectMapper;

    private final UserRepository userRepository;

    @Override
    public BaseResponse handle(BaseRequest request) {
        LogoutRequest logoutRequest = objectMapper.convertValue(request.getMessageBody(), LogoutRequest.class);

        Optional<AuthToken> opToken = authTokenRepository.findByToken(logoutRequest.getToken());
        User user = userRepository.findByEmail(logoutRequest.getEmail());

        if (opToken.isEmpty() || user == null) {
            throw new NotValidFieldException("User with email or token not found",
                    new BaseResponse(request.getMsgId(), MessageCode.AUTH_EMAIL_OR_TOKEN_NOT_FOUND.getCode(),
                            MessageCode.AUTH_EMAIL_OR_TOKEN_NOT_FOUND.getDescription(),
                            new LogoutRequest(logoutRequest.getEmail(), logoutRequest.getToken())));
        }

        if (!Objects.equals(opToken.get().getUser().getId(), user.getId())) {
            throw new NotValidFieldException("User token mismatch with user",
                    new BaseResponse(request.getMsgId(), MessageCode.AUTH_TOKEN_MISMATCH.getCode(),
                            MessageCode.AUTH_TOKEN_MISMATCH.getDescription(),
                            new LogoutRequest(logoutRequest.getEmail(), logoutRequest.getToken())));
        }


        authService.logout(logoutRequest.getToken());

        return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(), MessageCode.SUCCESS.getDescription(),
                new LogOutAnswer(logoutRequest.getEmail()));
    }
}
