/**
 * Pure mapping from the marketing website's raw inquiry payload into the
 * fields the CRM email templates need.
 *
 * The website dual-writes each form submission's body verbatim into
 * `website_submissions.payload` (snake_case keys). There is no `clients` /
 * `interests` row for a raw submission, so the email path reads straight from
 * the payload. Kept pure + dependency-free so it is trivially unit-testable
 * and defensive: any missing or non-string field degrades to '' or null
 * rather than throwing.
 */

export interface InquiryFields {
  firstName: string;
  lastName: string;
  fullName: string;
  email: string;
  phone: string;
  /** From the berth form's `berth` field (the mooring number). */
  mooringNumber: string | null;
  /** From the residence form's `address` field. */
  placeOfResidence: string | null;
  /** From the contact form's free-text `comments` field. */
  comments: string | null;
  /** The contact form's `interest` (string or string[]) joined for display. */
  interestType: string | null;
  /** The residence form's `residence_types` multi-select (villa types chosen). */
  residenceTypes: string[];
  /** The register form's `method_of_contact` preference: 'email' | 'phone'. */
  preferredContact: 'email' | 'phone' | null;
}

function str(value: unknown): string {
  return typeof value === 'string' ? value.trim() : '';
}

export function extractInquiryFields(payload: Record<string, unknown>): InquiryFields {
  const firstName = str(payload.first_name);
  const lastName = str(payload.last_name);
  const email = str(payload.email);
  const phone = str(payload.phone);
  const mooringNumber = str(payload.berth) || null;
  const placeOfResidence = str(payload.address) || null;
  const comments = str(payload.comments) || null;

  const rawInterest = payload.interest;
  const interestType = Array.isArray(rawInterest)
    ? rawInterest.filter((v): v is string => typeof v === 'string').join(', ') || null
    : str(rawInterest) || null;

  // The residence form posts `residence_types` as an array of villa-type
  // strings. Defensively coerce a lone string to a single-item array so a
  // future single-select form variant still maps cleanly.
  const rawResidenceTypes = payload.residence_types;
  const residenceTypes = Array.isArray(rawResidenceTypes)
    ? rawResidenceTypes.filter((v): v is string => typeof v === 'string' && v.trim() !== '')
    : str(rawResidenceTypes)
      ? [str(rawResidenceTypes)]
      : [];

  const methodOfContact = str(payload.method_of_contact).toLowerCase();
  const preferredContact =
    methodOfContact === 'email' ? 'email' : methodOfContact === 'phone' ? 'phone' : null;

  return {
    firstName,
    lastName,
    fullName: `${firstName} ${lastName}`.trim(),
    email,
    phone,
    mooringNumber,
    placeOfResidence,
    comments,
    interestType,
    residenceTypes,
    preferredContact,
  };
}
