import type { CreateVolunteerRoleBody } from "@/features/opportunities/services/roles";
import type { VolunteerOpportunityRoleRecord } from "@/features/opportunities/rolesAndTeamsRecord";
import type { Language } from "@/store/languageStore";

/**
 * The create/update body for a volunteer role, from the one-language form.
 *
 * `VolunteerOpportunityRoleController::store()` requires `role_name_en` **and**
 * `role_name_ar`, but the editor has a single name field and a single
 * instructions field. The untouched language falls back to whatever was already
 * stored (editing) or duplicates the typed value (creating) — with one text box
 * that is the best available content for it.
 *
 * Written out per language rather than with computed keys (`role_name_${lang}`).
 * Computed keys gave the object an index signature, and an index signature
 * satisfies *any* required-key check — which is exactly how a wrong key reached
 * `POST /opportunity-feedbacks/` unnoticed for the whole life of that screen.
 * Spelling the four fields out is what lets `tsc` check them.
 */
export function volunteerRoleRequestBody({
  roleName,
  instructions,
  participantsNeeded,
  opportunityId,
  language,
  savedRole,
}: {
  roleName: string;
  instructions: string;
  /** The form field is a string; the endpoint validates `integer`, `min:1`. */
  participantsNeeded: string | number;
  opportunityId: string | number;
  language: Language;
  /** The role being edited, if any — the source of the other language's text. */
  savedRole?: VolunteerOpportunityRoleRecord | null;
}): CreateVolunteerRoleBody {
  const typingArabic = language === "ar";

  return {
    role_name_ar: typingArabic ? roleName : savedRole?.role_name_ar || roleName,
    role_name_en: typingArabic ? savedRole?.role_name_en || roleName : roleName,
    instructions_ar: typingArabic
      ? instructions
      : savedRole?.instructions_ar || instructions,
    instructions_en: typingArabic
      ? savedRole?.instructions_en || instructions
      : instructions,
    participants_needed: Number(participantsNeeded),
    /* `Number(...)`: validated `integer`. Laravel coerces a numeric string,
       but the type states what the endpoint means. */
    opportunity_id: Number(opportunityId),
  };
}

/** Form fields that can carry a server field error. */
export const ROLE_FORM_FIELDS = ["role_name", "instructions", "participants_needed"] as const;

/** The body carries both language columns, so each maps back to its one field. */
export const ROLE_FIELD_ALIASES: Record<string, string> = {
  role_name_en: "role_name",
  role_name_ar: "role_name",
  instructions_en: "instructions",
  instructions_ar: "instructions",
};
