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

import jdk.jfr.Description;
import lombok.Data;
import lombok.Setter;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.host.service.HostOwnerService;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.review.SendReviewComplaintEMailTaskData;
import ru.yandex.webmaster3.core.worker.client.WorkerClient;
import ru.yandex.webmaster3.storage.review.ComplaintService;
import ru.yandex.webmaster3.storage.ugc.UGCIntegrationService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;

/**
 * author: ishalaru
 * DATE: 19.07.2019
 */
@WriteAction
@ru.yandex.autodoc.common.doc.annotation.Description(value = "Пожаловаться на отзыв")
@Category("comment")
@Component("/comment/complaint")
public class SendComplaintEmailAction extends
        AbstractUserVerifiedHostAction<SendComplaintEmailAction.Request, SendComplaintEmailAction.Response> {

    private final ComplaintService complaintService;
    private final WorkerClient workerClient;
    private final UGCIntegrationService ugcIntegrationService;
    private final HostOwnerService hostOwnerService;

    @Autowired
    public SendComplaintEmailAction(ComplaintService complaintService,
                                    @Qualifier("lbWorkerClient") WorkerClient workerClient,
                                    UGCIntegrationService ugcIntegrationService,
                                    HostOwnerService hostOwnerService) {
        this.complaintService = complaintService;
        this.workerClient = workerClient;
        this.ugcIntegrationService = ugcIntegrationService;
        this.hostOwnerService = hostOwnerService;
    }


    @Override
    public Response process(Request request) {

        final WebmasterHostId mascotHostOwner = hostOwnerService.getMascotHostOwner(request.getHostId());
        final String site = mascotHostOwner.getReadableHostname();
        UGCIntegrationService.UGCReview ugcReview = ugcIntegrationService.loadFromDigest(request.getReviewId());
        if (ugcReview == null) {
            return new Response.ErrorResponseReviewIdNotFound();
        }

        String id = ugcReview.getAuthor().getId();
        if (id.startsWith("/user/")) {
            id = id.replace("/user/", "");
        } else {
            return new Response.ErrorIncorrectUGCData();
        }
        if (!complaintService.insert(request.getHostId(), request.getReviewId(), request.getUserId())) {
            return new Response.ErrorResponseDuplicateComplaint();
        }
        final var sendData = SendReviewComplaintEMailTaskData.builder()
                .hostId(mascotHostOwner)
                .userId(request.getUserId())
                .reviewId(request.getReviewId())
                .reviewText(ugcReview.getText())
                .reviewTime(ugcReview.getTime())
                .reviewUserId(Long.valueOf(id))
                .complaintText(request.getComplaintText())
                .complaintTime(DateTime.now()).build();

        if (!workerClient.checkedEnqueueTask(sendData)) {
            complaintService.delete(request.getHostId(), request.getReviewId());
            return new Response.ErrorResponseImpl();
        }

        return new Response.NormalResponseImpl();
    }

    @Data
    public static class Request extends AbstractUserVerifiedHostRequest {
        @Setter(onMethod = @__({@Description("Уникальный ID отзыва"), @RequestQueryProperty(required = true)}))
        private String reviewId;
        @Setter(onMethod = @__({@Description("Текс жалобы"), @RequestQueryProperty(required = true)}))
        private String complaintText;
    }

    public interface Response extends ActionResponse {
        class NormalResponseImpl implements Response, ActionResponse.NormalResponse {
        }

        enum SendComplaintEmailErrorType {
            MESSAGE_UNSEND,
            DUPLICATE_COMPLAINT,
            REVIEW_ID_NOT_FOUND,
            INCORRECT_UGC_DATA
        }

        class ErrorResponseImpl implements Response, ActionResponse.ErrorResponse {
            @Override
            public SendComplaintEmailErrorType getCode() {
                return SendComplaintEmailErrorType.MESSAGE_UNSEND;
            }
        }

        class ErrorResponseDuplicateComplaint implements Response, ActionResponse.ErrorResponse {
            @Override
            public Enum<?> getCode() {
                return SendComplaintEmailErrorType.DUPLICATE_COMPLAINT;
            }
        }

        class ErrorResponseReviewIdNotFound implements Response, ActionResponse.ErrorResponse {

            @Override
            public Enum<?> getCode() {
                return SendComplaintEmailErrorType.REVIEW_ID_NOT_FOUND;
            }
        }

        class ErrorIncorrectUGCData implements Response, ActionResponse.ErrorResponse {

            @Override
            public Enum<?> getCode() {
                return SendComplaintEmailErrorType.INCORRECT_UGC_DATA;
            }
        }
    }
}

