import * as Yup from "yup";
import i18n from "@/lib/i18n/config";
import { YupWhatsAppContact } from "@/features/shared/schemas";
import { isSignupSocialLink, normalizeSignupSocialLink, type SignupSocialPlatform } from "./signupSocialLinks";
export const ORGANIZATION_SOCIAL_KEYS = ["facebook_link", "instagram_link", "linkedin_link", "twitter_link", "whatsapp_link"] as const;
export interface OrganizationSignupExtrasValues {
  profile_pic: File[];
  _interests: string[];
  facebook_link: string; instagram_link: string; linkedin_link: string; twitter_link: string; whatsapp_link: string;
}
export const organizationSignupExtras: OrganizationSignupExtrasValues = { profile_pic: [], _interests: [], facebook_link: "", instagram_link: "", linkedin_link: "", twitter_link: "", whatsapp_link: "" };
export function organizationSignupRules() {
  const required = () => i18n.t("COMMON.REQUIRED.FIELD");
  const social = (platform: SignupSocialPlatform) => Yup.string().trim().max(255)
    .test("platform-host", () => i18n.t("COMMON.SOCIAL_PLATFORM_LINK_REQUIRED", { platform: i18n.t(`COMMON.SOCIAL_${platform.toUpperCase()}`) }), value => !value || isSignupSocialLink(platform, value));
  return {
    profile_pic: Yup.array().min(1, required).max(1).of(Yup.mixed<File>().test("image", () => i18n.t("COMMON.REVIEW_IMAGE_LIMIT"), file => !file || (["image/jpeg", "image/png", "image/webp"].includes(file.type) && file.size <= 10 * 1024 * 1024))),
    facebook_link: social("facebook").test("one-contact", () => i18n.t("COMMON.ORGANIZATION_SOCIAL_REQUIRED"), function () { return ORGANIZATION_SOCIAL_KEYS.some(key => Boolean(this.parent[key]?.trim())); }),
    instagram_link: social("instagram"), linkedin_link: social("linkedin"), twitter_link: social("twitter"),
    whatsapp_link: YupWhatsAppContact.max(255), // `users.whatsapp_link` is varchar(255) (backend `WhatsAppContact::PROFILE_MAX`)
  };
}
export function appendOrganizationSignupExtras(data: FormData, values: OrganizationSignupExtrasValues) {
  if (values.profile_pic[0]) data.append("profile_pic", values.profile_pic[0]);
  values._interests.forEach((id, index) => data.append(`interest_ids[${index}]`, id));
  for (const key of ORGANIZATION_SOCIAL_KEYS) data.append(key, key === "whatsapp_link" ? values[key].trim() : normalizeSignupSocialLink(values[key]));
}
/**
 * The sign-up intent the API expects. A team is its own account type
 * (`voluntary_team`) and never sends an organization type: the backend refuses
 * the «Volunteer Team» type id on `organizer_type` (OrganizationIntake::organizerTypeRule).
 * The form still holds that id so its license rules resolve for a team.
 */
export function appendSignupAccountType(data: FormData, isTeam: boolean, organizerType: string | undefined) {
  data.append("user_type", signupUserType(isTeam));
  if (!isTeam) data.append("organizer_type", organizerType ?? "");
}
export function signupUserType(isTeam: boolean) {
  return isTeam ? "voluntary_team" : "organization";
}
