package ru.micord.ervu.account_applications.service.processor.impl;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;
import ru.micord.ervu.account_applications.dao.RecruitmentSolutionDao;
import ru.micord.ervu.account_applications.db_beans.public_.tables.records.RecruitmentSolutionRecord;
import ru.micord.ervu.account_applications.model.RecruitmentSolutionData;
import ru.micord.ervu.account_applications.service.processor.LinkDataProcessor;

/**
 * @author Adel Kalimullin
 */
@Component
public class RecruitmentSolutionProcessor
    implements LinkDataProcessor<RecruitmentSolutionData, RecruitmentSolutionRecord> {
  private final RecruitmentSolutionDao dao;

  public RecruitmentSolutionProcessor(RecruitmentSolutionDao dao) {
    this.dao = dao;
  }

  public void upsertRecruitmentSolutions(String recruitmentId, Set<String> incomingIds) {
    List<String> existingIds = dao.getSolutionIdsByRecruitmentId(recruitmentId);
    List<String> toDelete = existingIds.stream()
        .filter(id -> !incomingIds.contains(id))
        .toList();

    Set<String> toAdd = incomingIds.stream()
        .filter(id -> !existingIds.contains(id))
        .collect(Collectors.toSet());

    if (!toDelete.isEmpty()) {
      dao.deleteRecruitmentSolutionsByRecruitmentIdAndSolutionIds(recruitmentId, toDelete);
    }

    if (!toAdd.isEmpty()) {
      List<RecruitmentSolutionRecord> recordsToAdd = toAdd.stream()
          .map(id -> mapToRecord(new RecruitmentSolutionData(recruitmentId, id)))
          .toList();
      dao.mergeRecords(recordsToAdd);
    }
  }

  @Override
  public void deleteLink(RecruitmentSolutionData data) {
    RecruitmentSolutionRecord recruitmentSolutionRecord = mapToRecord(data);
    dao.deleteRecruitmentSolution(recruitmentSolutionRecord);
  }

  @Override
  public void upsertData(RecruitmentSolutionData data) {
    RecruitmentSolutionRecord recruitmentSolutionRecord = mapToRecord(data);
    dao.upsertData(recruitmentSolutionRecord);
  }

  @Override
  public void changeActiveStatus(List<String> ids, boolean active) {
    throw new UnsupportedOperationException("Not supported yet.");
  }

  @Override
  public Class<RecruitmentSolutionData> getType() {
    return RecruitmentSolutionData.class;
  }

  @Override
  public RecruitmentSolutionRecord mapToRecord(RecruitmentSolutionData data) {
    RecruitmentSolutionRecord recruitmentSolutionRecord = dao.newRecord();
    recruitmentSolutionRecord.setRecruitmentId(data.getId());
    recruitmentSolutionRecord.setSolutionId(data.getSolutionId());
    return recruitmentSolutionRecord;
  }
}
