package com.dev.registration.company.mappers;

import static java.util.Optional.ofNullable;

import static com.strategyobject.sokit.extensions.core.utils.CollectionUtils.orSet;

import com.dev.registration.company.data.CompanyEntity;
import com.dev.registration.company.data.ShareholderEntity;
import com.dev.registration.company.data.dm.ShareholderEntryDto;
import jakarta.inject.Singleton;
import java.util.*;
import lombok.RequiredArgsConstructor;

import com.strategyobject.sokit.extensions.core.context.SOContext;
import com.strategyobject.sokit.extensions.core.mappers.SubEntityCollectionMapper;
import com.strategyobject.sokit.extensions.core.utils.ObjectUtils;

@Singleton
@RequiredArgsConstructor
public class ShareholdersMapper
    extends SubEntityCollectionMapper<CompanyEntity, ShareholderEntity, ShareholderEntryDto> {

  private final CompanyEntityMapper mapper;

  @Override
  public Optional<ShareholderEntity> createSubEntity(
      SOContext ctx, ShareholderEntryDto entry, CompanyEntity parent) {
    if (entry == null) {
      return Optional.empty();
    }
    final var entity = new ShareholderEntity();
    entity.setId(UUID.randomUUID().toString());
    entity.setParent(parent);
    return Optional.of(entity);
  }

  @Override
  public Collection<ShareholderEntity> computeIfAbsent(SOContext ctx, CompanyEntity parent) {
    parent.setShareholders(orSet(parent.getShareholders()));
    return parent.getShareholders();
  }

  @Override
  public boolean idEquals(ShareholderEntryDto entry, ShareholderEntity entity) {
    return ofNullable(entry)
        .map(ShareholderEntryDto::getId)
        .filter(ObjectUtils::isNotEmpty)
        .map(id -> id.equals(entity.getId()))
        .orElse(false);
  }

  @Override
  public void map(SOContext ctx, ShareholderEntryDto entry, ShareholderEntity entity) {
    mapper.map(entry, entity);
  }
}
