/** Shared (client + server) inquiry validation. */

export type InquiryInput = {
  name: string;
  company: string;
  email: string;
  phone: string;
  subject: string;
  message: string;
  /** Honeypot — must stay empty. */
  website?: string;
  locale?: string;
};

export type FieldError = "required" | "email" | "phone" | "tooShort" | "tooLong";
export type InquiryErrors = Partial<Record<keyof InquiryInput, FieldError>>;

export const LIMITS = { name: 120, company: 160, email: 200, phone: 40, subject: 120, message: 4000, messageMin: 20 };

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const PHONE_RE = /^\+?[0-9\s().-]{7,}$/;

export function normalise(raw: Partial<Record<keyof InquiryInput, unknown>>): InquiryInput {
  const s = (v: unknown) => (typeof v === "string" ? v.trim() : "");
  return {
    name: s(raw.name),
    company: s(raw.company),
    email: s(raw.email),
    phone: s(raw.phone),
    subject: s(raw.subject),
    message: s(raw.message),
    website: s(raw.website),
    locale: s(raw.locale),
  };
}

export function validate(v: InquiryInput): InquiryErrors {
  const e: InquiryErrors = {};
  const need = (k: keyof InquiryInput, max: number) => {
    const val = v[k] ?? "";
    if (!val) e[k] = "required";
    else if (val.length > max) e[k] = "tooLong";
  };
  need("name", LIMITS.name);
  need("company", LIMITS.company);
  need("email", LIMITS.email);
  need("subject", LIMITS.subject);
  need("message", LIMITS.message);
  if (!e.email && !EMAIL_RE.test(v.email)) e.email = "email";
  if (v.phone) {
    if (v.phone.length > LIMITS.phone) e.phone = "tooLong";
    else if (!PHONE_RE.test(v.phone)) e.phone = "phone";
  }
  if (!e.message && v.message.length < LIMITS.messageMin) e.message = "tooShort";
  return e;
}
