package ru.yandex.webmaster3.storage.review.dao;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.DataMapper;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;


/**
 * @author: iceflame
 * DATE: 31.08.2021
 */
@Repository
public class ReviewComplaintYDao extends AbstractYDao {
    public ReviewComplaintYDao() {
        super(PREFIX_WEBMASTER3, "review_complaint");
    }

    public boolean insertIfNotExist(WebmasterHostId hostId, String reviewId, Long userId) {
        if (!check(hostId, Collections.singleton(reviewId)).isEmpty()) {
            return false;
        }
        upsert(F.HOST_ID.value(hostId),
                F.REVIEW_ID.value(reviewId),
                F.USER_ID.value(userId),
                F.LAST_UPDATE.value(DateTime.now()))
                .execute();
        return true;
    }

    public void delete(WebmasterHostId hostId, String reviewId) {
        delete().where(F.HOST_ID.eq(hostId))
                .and(F.REVIEW_ID.eq(reviewId))
                .execute();
    }

    public void deleteForUser(long userId) {
        var sel = select(PK_MAPPER).secondaryIndex(USER_ID_INDEX).where(F.USER_ID.eq(userId)).getStatement();
        delete().on(sel).execute();
    }

    public List<String> check(WebmasterHostId hostId, Collection<String> reviewIds) {
        return select(MAPPER)
                .where(F.HOST_ID.eq(hostId))
                .and(F.REVIEW_ID.in(reviewIds))
                .queryForList();
    }

    private static final DataMapper<String> MAPPER = DataMapper.create(
            F.REVIEW_ID,
            (commentId) -> commentId
    );

    private static final DataMapper<Pair<WebmasterHostId, String>> PK_MAPPER = DataMapper.create(
            F.HOST_ID, F.REVIEW_ID, Pair::of
    );

    private interface F {
        Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        Field<String> REVIEW_ID = Fields.stringField("review_id");
        Field<Long> USER_ID = Fields.longField("user_id");
        Field<DateTime> LAST_UPDATE = Fields.jodaDateTimeField("last_update");
    }
}
