package ru.yandex.webmaster3.storage.settings.history;

import java.util.List;

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

import ru.yandex.webmaster3.core.util.enums.EnumResolver;
import ru.yandex.webmaster3.storage.user.UserTakeoutDataProvider;
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;

@Repository
public class TurboSettingsHistoryYDao extends AbstractYDao implements UserTakeoutDataProvider {
    private static final String TABLE_NAME = "turbo_settings_history";

    protected TurboSettingsHistoryYDao() {
        super(PREFIX_INTERNAL, TABLE_NAME);
    }

    public void insert(SettingsHistoryService.LogSettingInfo info) {
        upsert(
                F.TYPE.value(info.getType()),
                F.USER_ID.value(info.getUserId()),
                F.NEW_STATE.value(info.getNewState()),
                F.HOST_ID.value(info.getHostId()),
                F.UPDATE_DATE.value(info.getUpdateDate())
        ).execute();
    }

    public List<SettingsHistoryService.LogSettingInfo> changesForHostAndType(String hostId, SettingsHistoryType type) {
        return select(MAPPER)
                .where(F.HOST_ID.eq(hostId))
                .and(F.TYPE.eq(type))
                .queryForList(Pair.of(F.UPDATE_DATE, SettingsHistoryService.LogSettingInfo::getUpdateDate));
    }

    @Override
    public @NotNull List<String> getTakeoutTables() {
        // тут специально ничего не удаляем
        return List.of(
                getTablePath()
        );
    }

    private static final DataMapper<SettingsHistoryService.LogSettingInfo> MAPPER = DataMapper.create(
            F.USER_ID, F.TYPE, F.NEW_STATE,
            F.HOST_ID, F.UPDATE_DATE,
            SettingsHistoryService.LogSettingInfo::new
    );

    private static final class F {
        static final Field<String> HOST_ID = Fields.stringField("host_id");
        static final Field<SettingsHistoryType> TYPE = Fields.stringEnumField("type",
                EnumResolver.er(SettingsHistoryType.class)).makeOptional();
        static final Field<DateTime> UPDATE_DATE = Fields.jodaDateTimeField("update_date");

        static final Field<String> NEW_STATE = Fields.stringField("new_state").makeOptional();
        static final Field<Long> USER_ID = Fields.longField("user_id");

    }
}
