import type { VolunteerOpportunityRoleRecord } from "@/features/opportunities/rolesAndTeamsRecord";

/** The three fields the role form edits. All strings — the inputs are text. */
export interface RoleFormValues {
  role_name: string;
  instructions: string;
  participants_needed: string;
}

/**
 * Seeds the role form, from the saved role when editing and from the
 * outstanding participant count when adding.
 *
 * Extracted from the modal because every rule in it is a response-contract
 * detail rather than markup:
 *
 * - the localized columns are **exactly** `role_name_en` / `role_name_ar` (and
 *   the `instructions_*` pair), so the language picks a branch rather than
 *   building a key. `role[`role_name_${language}`]` returned `undefined` for
 *   any other language value, and the index signature on the old local `Role`
 *   type meant nothing complained.
 * - all four localized columns are **nullable**, so `|| ""` rather than a
 *   cast. `String(null)` would have put the literal text `"null"` in the
 *   field.
 * - `participants_needed` is a **number** on the payload and a string in the
 *   form. `!= null` rather than `||` because a role needing `0` participants
 *   is a real saved value, and `||` would have replaced it with the
 *   add-mode default.
 */
export function roleFormInitialValues({
  savedRole,
  isEditing,
  language,
  participantsStillNeeded,
}: {
  savedRole: VolunteerOpportunityRoleRecord | undefined;
  /** True when a role id was supplied, even before its fetch resolves. */
  isEditing: boolean;
  language: string;
  participantsStillNeeded: number;
}): RoleFormValues {
  const isArabic = language === "ar";

  return {
    role_name:
      (isArabic ? savedRole?.role_name_ar : savedRole?.role_name_en) || "",
    instructions:
      (isArabic ? savedRole?.instructions_ar : savedRole?.instructions_en) || "",
    participants_needed:
      savedRole?.participants_needed != null
        ? String(savedRole.participants_needed)
        : isEditing
          ? ""
          : String(participantsStillNeeded),
  };
}
