import { z } from "zod";
import { enquirySchema, interests, type Enquiry } from "./contact-schema";
export const MAX_AMOUNT = 1_000_000;
const numbersOnly = (label: string) =>
  `Enter ${label} in dollars, using numbers only.`;
const tooLarge = `Enter an amount of no more than $${MAX_AMOUNT.toLocaleString("en-SG")}.`;
const amount = (
  label: string,
  atLeast?: { minimum: number; message: string },
) =>
  z
    .string()
    .trim()
    .min(1, "This field is required.")
    .max(24, numbersOnly(label))
    .transform((value) => value.replace(/^s?\$|[,\s]/gi, ""))
    .pipe(z.string().regex(/^\d+(\.\d{1,2})?$/, numbersOnly(label)))
    .transform(Number)
    .pipe(
      (atLeast
        ? z.number().min(atLeast.minimum, atLeast.message)
        : z.number()
      ).max(MAX_AMOUNT, tooLarge),
    );
export const quickApplySchema = z.object({
  name: enquirySchema.shape.name,
  phone: enquirySchema.shape.phone,
  email: enquirySchema.shape.email,
  interest: z.enum(interests, "Choose the purpose of your loan."),
  monthlyIncome: amount("your monthly income"),
  loanAmount: amount("your desired loan amount", {
    minimum: 1,
    message: "Enter your desired loan amount.",
  }),
});
export const quickApplyRequestSchema = quickApplySchema
  .extend({
    website: z.string().max(2048).optional().default(""),
    turnstileToken: z.string().min(1).max(2048),
    requestId: z.uuid(),
  })
  .strict();
export type QuickApply = z.output<typeof quickApplySchema>;
export const quickApplyFieldNames = Object.keys(
  quickApplySchema.shape,
) as (keyof QuickApply)[];
const sgd = (value: number) =>
  `SGD ${value.toLocaleString("en-SG", { maximumFractionDigits: 2 })}`;
export function quickApplyEnquiry(data: QuickApply): Enquiry {
  return {
    name: data.name,
    email: data.email,
    phone: data.phone,
    interest: data.interest,
    subject: "Quick apply call-back request",
    message: `Monthly income: ${sgd(data.monthlyIncome)}\nDesired loan amount: ${sgd(data.loanAmount)}\n\nSubmitted through the quick apply form; the visitor is expecting a call back.`,
  };
}
