package com.dev.registration.company.flow.events;

import com.dev.registration.company.data.CompanyEntity;
import com.dev.registration.company.document.CompanyDocument;
import com.dev.registration.company.document.Operations;
import com.dev.registration.company.document.StartOperations;
import com.dev.registration.company.document.States;
import com.dev.registration.company.document.document.events.CompanyOperationEvent;
import com.dev.registration.company.flow.exceptions.ExceedPercentageException;
import lombok.RequiredArgsConstructor;

import com.strategyobject.sokit.extensions.document.DocumentTransaction;
import com.strategyobject.sokit.extensions.document.api.annotations.DocumentAware;

@DocumentAware(CompanyDocument.class)
@RequiredArgsConstructor
public class ValidateShare implements CompanyOperationEvent {

  @Override
  public void execute(
      DocumentTransaction<States, StartOperations, Operations, String, CompanyEntity> transaction) {
    final var entity = transaction.entity();
    if (entity == null) {
      return;
    }
    double totalPercentage = 0;

    for (var shareholder : transaction.entity().getShareholders()) {
      totalPercentage += shareholder.getPercentage();
      if (totalPercentage > 100.0) {
        throw ExceedPercentageException.builder().build().path("percentage");
      }
    }
  }
}
