import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms";

import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
import { ProductType } from "@bitwarden/common/enums";

/**
 * Checks if the limit of free organization seats has been reached when adding new users
 * @param organization An object representing the organization
 * @param allOrganizationUserEmails An array of strings with existing user email addresses
 * @param errorMessage A localized string to display if validation fails
 * @returns A function that validates an `AbstractControl` and returns `ValidationErrors` or `null`
 */
export function freeOrgSeatLimitReachedValidator(
  organization: Organization,
  allOrganizationUserEmails: string[],
  errorMessage: string
): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (control.value === "" || !control.value) {
      return null;
    }

    const newEmailsToAdd = control.value
      .split(",")
      .filter(
        (newEmailToAdd: string) =>
          newEmailToAdd &&
          !allOrganizationUserEmails.some((existingEmail) => existingEmail === newEmailToAdd)
      );

    return organization.planProductType === ProductType.Free &&
      allOrganizationUserEmails.length + newEmailsToAdd.length > organization.seats
      ? { freePlanLimitReached: { message: errorMessage } }
      : null;
  };
}
