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

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.*;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.user.service.InitializedUsersService;

import java.util.UUID;

/**
 * @author leonidrom
 */
@Slf4j
@ReadAction
@Category("user")
@Description(value = "Возвращает паспортный id пользователя по его UUID.")
@Component("/user/idByUUID")
public class GetUserIdByUUIDAction extends Action<GetUserIdByUUIDAction.Req, GetUserIdByUUIDAction.Resp> {
    private static final String FAIL_MESSAGE = "User not found";

    private final InitializedUsersService initializedUsersService;

    @Autowired
    public GetUserIdByUUIDAction(InitializedUsersService initializedUsersService) {
        this.initializedUsersService = initializedUsersService;
    }

    @Override
    public Resp process(Req request) {
        Long userId = initializedUsersService.getIdByUUIDUncached(request.userUUID);
        if (userId == null) {
            throw new WebmasterException(FAIL_MESSAGE,
                    new WebmasterErrorResponse.InternalUnknownErrorResponse(getClass(), FAIL_MESSAGE));
        }

        return new Resp(userId, request.userUUID);
    }

    public static class Req implements ActionRequest {
        private UUID userUUID;

        @RequestQueryProperty(required = true)
        public void setUserUUID(UUID userUUID) {
            this.userUUID = userUUID;
        }
    }

    public static class Resp implements ActionResponse.NormalResponse {
        private final long userId;
        private final UUID userUUID;

        public Resp(long userId, UUID userUUID) {
            this.userId = userId;
            this.userUUID = userUUID;
        }

        @Description("паспортный id пользователя")
        public long getUserId() {
            return userId;
        }

        @Description("ереданный UUID пользователя")
        public UUID getUserUUID() {
            return userUUID;
        }
    };
}
