package ru.yandex.webmaster3.internal.user.takeout;

import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.util.json.JsonMapping;
import ru.yandex.webmaster3.internal.common.InternalAction;
import ru.yandex.webmaster3.internal.common.security.InternalGrant;
import ru.yandex.webmaster3.storage.postpone.PostponeActionYDao;
import ru.yandex.webmaster3.storage.postpone.PostponeOperationType;
import ru.yandex.webmaster3.core.user.takeout.UserTakeoutRequestType;
import ru.yandex.webmaster3.storage.user.service.UserTakeoutQueryData;
import ru.yandex.webmaster3.storage.user.service.UserTakeoutService;

/**
 * @author leonidrom
 */
@Component("/1/takeout/delete")
@WriteAction
@Slf4j
public class UserTakeoutDeleteAction extends InternalAction<UserTakeoutDeleteRequest, UserTakeoutDeleteResponse> {
    private final UserTakeoutService userTakeoutService;
    private final PostponeActionYDao postponeActionYDao;

    @Autowired
    public UserTakeoutDeleteAction(UserTakeoutService userTakeoutService, PostponeActionYDao postponeActionYDao) {
        super(InternalGrant.USER_TAKEOUT);
        this.userTakeoutService = userTakeoutService;
        this.postponeActionYDao = postponeActionYDao;
    }

    @Override
    public UserTakeoutDeleteResponse process(UserTakeoutDeleteRequest request) throws WebmasterException {
        try {
            return doProcess(request);
        } catch (Exception e) {
            // нужно для того, чтобы отдать ошибку в формате, ожидаемом takeout
            log.error("Error while processing action", e);
            return new UserTakeoutDeleteResponse.ErrorResponse("internal", "Error while processing action");
        }
    }

    public UserTakeoutDeleteResponse doProcess(UserTakeoutDeleteRequest request) throws WebmasterException {
        log.info("Takeout delete request {}", request.getRequestId());
        long userId = request.getUserId();
        var takeoutReq = userTakeoutService.getRequest(userId);
        if (takeoutReq != null && !takeoutReq.getStatus().isTerminal()) {
            return new UserTakeoutDeleteResponse.ErrorResponse("internal", "Request already exists");
        }

        takeoutReq = userTakeoutService.createRequest(userId, UserTakeoutRequestType.DELETE);
        postponeActionYDao.insert(DateTime.now().plus(UserTakeoutService.GET_RETRY_PERIOD),
                PostponeOperationType.USER_TAKEOUT_DELETE,
                JsonMapping.writeValueAsString(new UserTakeoutQueryData(userId, takeoutReq.getRequestId())));

        return new UserTakeoutDeleteResponse.NormalResponse();
    }
}