export type ApprovalAssigneeType = 'DEPT' | 'ROLE' | 'USER';

export interface ApplicantDeptRestrictionStepState<TTarget = unknown> {
  assigneeTargetIds: Array<number | string>;
  assigneeTargets: TTarget[];
  assigneeType: ApprovalAssigneeType;
  includeChildrenByTarget: Record<string, boolean>;
  restrictToApplicantDept: boolean;
}

export function normalizeApplicantDeptRestriction(value: unknown) {
  return value === true || value === 1 || value === '1' || value === 'true';
}

export function needsApplicantDeptRestrictionConfirmation(
  step: ApplicantDeptRestrictionStepState,
  enabled: boolean,
) {
  return (
    enabled && step.assigneeType === 'DEPT' && step.assigneeTargetIds.length > 0
  );
}

export function applyApplicantDeptRestriction<TTarget>(
  step: ApplicantDeptRestrictionStepState<TTarget>,
  enabled: boolean,
) {
  if (enabled && step.assigneeType === 'DEPT') {
    step.assigneeType = 'ROLE';
    step.assigneeTargetIds = [];
    step.assigneeTargets = [];
    step.includeChildrenByTarget = {};
  }
  step.restrictToApplicantDept = enabled;
}

export function isApplicantDeptAssigneeTypeDisabled(
  restricted: boolean,
  assigneeType: ApprovalAssigneeType,
) {
  return restricted && assigneeType === 'DEPT';
}

export function serializeApplicantDeptRestriction(restricted: boolean) {
  return restricted ? 1 : 0;
}
