import * as yup from "yup";
import { normalizeEmail } from "@/lib/email";

/**
 * Shared yup email field with backend-matching normalization.
 *
 * Apply via `email: emailField()` (or `email: emailField("Custom required msg")`)
 * in any schema. The `.transform` runs at validation time, so `data.email`
 * arriving in onSubmit is already lowercased and trimmed.
 *
 * FORM CHECKLIST when adding a new email-bearing form:
 *   1. Use this `emailField()` in your yup schema.
 *   2. Call `normalizeEmail(data.email)` on the API payload (belt-and-suspenders).
 *   3. In `onError`, branch on `isEmailAlreadyExistsError(err)` -> setError("email", ...).
 */
export const emailField = (
  requiredMessage: string = "Email is required",
  invalidMessage: string = "Please enter a valid email address",
) =>
  yup
    .string()
    .transform((v) => normalizeEmail(v))
    .required(requiredMessage)
    .email(invalidMessage);
