package ru.micord.ervu.account_applications.dao;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Table;
import org.springframework.stereotype.Repository;
import ru.micord.ervu.account_applications.db_beans.public_.Tables;
import ru.micord.ervu.account_applications.db_beans.public_.tables.records.RecruitmentIpRecord;

/**
 * @author Adel Kalimullin
 */
@Repository
public class RecruitmentIpDao extends AbstractDataDao<RecruitmentIpRecord> {
  protected RecruitmentIpDao(DSLContext dsl) {
    super(dsl);
  }

  public boolean existsIpAddress(String ip) {
    return !getExistingIpAddresses(List.of(ip)).isEmpty();
  }

  public void deleteRecruitmentIp(RecruitmentIpRecord record) {
    Map<Field<String>, String> conditions = Map.of(
        Tables.RECRUITMENT_IP.RECRUITMENT_ID, record.getRecruitmentId(),
        Tables.RECRUITMENT_IP.IP_ADDRESS, record.getIpAddress()
    );

    deleteByValues(conditions);
  }

  public Set<String> getExistingIpAddresses(List<String> ips) {
    return getExistingValuesByField(Tables.RECRUITMENT_IP.IP_ADDRESS, ips);
  }

  public void deleteRecruitmentIpsByRecruitmentIdAndIps(String recruitmentId, List<String> ips) {
    deleteByFieldAndInValues(
        Tables.RECRUITMENT_IP.RECRUITMENT_ID, recruitmentId,
        Tables.RECRUITMENT_IP.IP_ADDRESS, ips
    );
  }

  public Set<String> getIpAddressesByRecruitmentId(String recruitmentId) {
    List<String> valuesByField = getValuesByField(
        Tables.RECRUITMENT_IP.IP_ADDRESS,
        Tables.RECRUITMENT_IP.RECRUITMENT_ID, recruitmentId
    );
    return new HashSet<>(valuesByField);
  }

  @Override
  protected Table<RecruitmentIpRecord> getTable() {
    return Tables.RECRUITMENT_IP;
  }
}
