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.SolutionRoleDao;
import ru.micord.ervu.account_applications.db_beans.public_.tables.records.SolutionRoleRecord;
import ru.micord.ervu.account_applications.model.SolutionRoleData;
import ru.micord.ervu.account_applications.service.processor.LinkDataProcessor;

/**
 * @author Adel Kalimullin
 */
@Component
public class SolutionRoleProcessor
    implements LinkDataProcessor<SolutionRoleData, SolutionRoleRecord> {
  private final SolutionRoleDao dao;

  public SolutionRoleProcessor(SolutionRoleDao dao) {
    this.dao = dao;
  }

  @Override
  public void deleteLink(SolutionRoleData data) {
    SolutionRoleRecord solutionRoleRecord = mapToRecord(data);
    dao.deleteSolutionRole(solutionRoleRecord);
  }

  public void upsertSolutionRoles(String solutionId, Set<String> incomingIds) {
    List<String> existingIds = dao.getRoleIdsBySolutionId(solutionId);
    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.deleteSolutionRolesBySolutionIdAndRoleIds(solutionId, toDelete);
    }

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

  @Override
  public void upsertData(SolutionRoleData data) {
    SolutionRoleRecord solutionRoleRecord = mapToRecord(data);
    dao.upsertData(solutionRoleRecord);
  }

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

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

  @Override
  public SolutionRoleRecord mapToRecord(SolutionRoleData data) {
    SolutionRoleRecord solutionRoleRecord = dao.newRecord();
    solutionRoleRecord.setRoleId(data.getRoleId());
    solutionRoleRecord.setSolutionId(data.getId());
    return solutionRoleRecord;
  }
}
