package ru.yandex.webmaster3.viewer.http.user.settings.notification;

import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.blackbox.service.BlackboxUsersService;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.notifications.service.UserNotificationSettingsService;
import ru.yandex.webmaster3.viewer.http.AbstractUserAction;

import java.util.Optional;

/**
 * @author avhaliullin
 */
@Description("Сохранить новый email для нотификаций")
@WriteAction
@Category("notifications")
@AllArgsConstructor(onConstructor_ = @Autowired)
public class UpdateNotificationEmailAction extends AbstractUserAction<UpdateNotificationEmailRequest, UpdateNotificationEmailResponse> {
    private static final Logger log = LoggerFactory.getLogger(UpdateNotificationEmailAction.class);

    private final BlackboxUsersService blackboxExternalYandexUsersService;
    private final UserNotificationSettingsService userNotificationSettingsService;

    @Override
    public UpdateNotificationEmailResponse process(UpdateNotificationEmailRequest request) {
        String email = request.getEmail();
        if (email != null) {
            Optional<String> normalizedEmailOpt;
            normalizedEmailOpt = blackboxExternalYandexUsersService.getNormalizedUserEmail(request.getUserId(), email);
            if (normalizedEmailOpt.isPresent()) {
                email = normalizedEmailOpt.get();
            } else {
                return new UpdateNotificationEmailResponse.NotValidatedEmailError();
            }
        }

        try {
            userNotificationSettingsService.saveEmail(request.getUserId(), email);
            return new UpdateNotificationEmailResponse.NormalResponse();
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Failed to save user email",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
    }
}
