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

import static com.dev.registration.company.document.security.SecurityAll.OFFICER;

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.CompanyAccessEvent;
import java.util.Optional;

import com.strategyobject.sokit.extensions.core.context.SOContext;
import com.strategyobject.sokit.extensions.document.api.annotations.DocumentAware;

@DocumentAware(CompanyDocument.class)
public class DefaultAccessEvent implements CompanyAccessEvent {

  @Override
  public String code() {
    return "default";
  }

  @Override
  public boolean accept(
      Phase phase,
      SOContext ctx,
      States startState,
      StartOperations startOperation,
      Operations operation,
      CompanyEntity entity) {
    // allow all authorized users to access the company
    // you can use user context and check against the entity

    // company should view only their own companies
    final var currentSubject = ctx.identity().getSubject();
    final var isOfficer = ctx.identity().hasAnyRole(OFFICER);
    if (!isOfficer && !Operations.SUBMIT.equals(operation) && entity != null) {
      return Optional.ofNullable(entity.getCreatorSubject())
          .map(subject -> subject.equals(currentSubject))
          .orElse(false);
    }

    return true;
  }
}
