/**
 * Small typed helpers for the Formik/Yup rules that three organization forms
 * share.
 *
 * Each of them replaces an `any` that was load-bearing in the sense that
 * nothing else would compile without it — not an `any` added to silence a
 * warning, but one standing in for a shape nobody had written down. Two were
 * worth writing down because the same five lines appeared in
 * `useCompleteDetails`, `useEntitiesRegistration` and
 * `organizerAccountValidation`, and a sixth copy would have been easy to get
 * subtly wrong.
 */

import { isLicenseExemptOrgType, isLicenseUploadRequired, type OrgTypeOption } from "@/data/orgTypes";

/**
 * What Yup hands a `.when(key, builder)` callback.
 *
 * Yup's own types declare this `any[]`: it passes an *array* of the sibling
 * values when `when` is given a list of keys, and — depending on version — the
 * bare value when given one key. Every call site here passes a single key and
 * then re-checks with `Array.isArray`, which is why the union is honest rather
 * than a cast.
 */
export type YupWhenValue = string | readonly string[] | undefined;

/** The single sibling value a one-key `.when()` is conditioned on. */
export function whenValue(raw: YupWhenValue): string {
  if (Array.isArray(raw)) return raw[0] ?? "";
  return (raw as string | undefined) ?? "";
}

/**
 * The option a form's `organizer_type` value refers to.
 *
 * The comparison is string-on-string because the form holds the id as a string
 * (`toChoiceOptions(…, (item) => String(item.id))`) while the raw choice id is
 * an integer — see `CHOICE_ID_COERCION` in `lib/choices.ts`. Both sides are
 * coerced here so a future change to either convention still matches.
 */
export function findOrgTypeOption(
  options: OrgTypeOption[],
  value: unknown
): OrgTypeOption | undefined {
  return options.find((option) => String(option.value) === String(value));
}

/** Dashboard metadata governs organization licensing; teams always require it. */
export function licenseNumberRequiredFor(options: OrgTypeOption[], value: unknown): boolean {
  const choice = findOrgTypeOption(options, value);
  if (choice?.rawValue === "Volunteer Team") return true;
  return choice?.licenseRequired ?? !isLicenseExemptOrgType(choice?.rawValue);
}

export function licenseUploadRequiredFor(
  options: OrgTypeOption[],
  value: unknown
): boolean {
  const choice = findOrgTypeOption(options, value);
  if (choice?.rawValue === "Volunteer Team") return true;
  return choice?.licenseDocumentRequired ?? isLicenseUploadRequired(choice?.rawValue);
}

/**
 * Sign-up licence rules. A team never carries an organization type (the
 * dropdown and `/choices/org_type/` both leave «Volunteer Team» out), and the
 * server requires its licence number and documents unconditionally
 * (`OrganizationLicenseRequirement::signupErrors`, PDF p.9).
 */
export function signupLicenseNumberRequired(isTeam: boolean, options: OrgTypeOption[], value: unknown): boolean {
  return isTeam || licenseNumberRequiredFor(options, value);
}

export function signupLicenseUploadRequired(isTeam: boolean, options: OrgTypeOption[], value: unknown): boolean {
  return isTeam || licenseUploadRequiredFor(options, value);
}

/** Default document cap; callers may supply their endpoint-specific limit. */
export const MAX_DOCUMENT_BYTES = 2 * 1024 * 1024;

/**
 * Whether every entry of a `documents` array is a `File` within the size cap.
 *
 * `unknown` rather than `File`: a Yup array test receives whatever the field
 * holds, and these pickers legitimately mix freshly-picked `File` objects with
 * already-stored records. The `instanceof` check is what separates them, so it
 * cannot be replaced by a type annotation.
 */
export function areDocumentsWithinSizeLimit(files: readonly unknown[], maximumBytes = MAX_DOCUMENT_BYTES): boolean {
  return files.every(
    (file) => file instanceof File && file.size <= maximumBytes
  );
}
