import { z } from "zod";
import rateLimit from "express-rate-limit";

/**
 * Input hardening for unauthenticated public intake (GRM) and other free-text
 * fields that are stored, rendered into HTML emails, and exported to CSV.
 *
 * Markup is **rejected** rather than silently stripped so the submitter gets an
 * explicit message instead of a mangled case, and probe payloads never reach the
 * grievance register. Everything else is normalised (whitespace, control
 * characters) before the length check runs.
 */

/** Opening/closing HTML tag, comment or doctype — `<img …>`, `<svg/…>`, `</script>`, `<!--`. */
const HTML_TAG = /<\s*(\/|!|[a-zA-Z])/;
/** `javascript:` / `vbscript:` URIs. */
const DANGEROUS_SCHEME = /\b(?:javascript|vbscript)\s*:/i;
/** `data:text/html,…` URIs. */
const DATA_HTML_URI = /\bdata\s*:\s*text\s*\/\s*html/i;
/** Inline event handlers — `onerror=`, `onload=`, `animationstart=`, … */
const EVENT_HANDLER =
  /\bon(?:error|load|click|focus|blur|change|submit|toggle|mouseover|mouseenter|animationstart|begin)\s*=/i;

/** Reason a value looks like script/markup, or `null` when it is clean. */
export function markupIssue(value: string): string | null {
  if (
    HTML_TAG.test(value) ||
    DANGEROUS_SCHEME.test(value) ||
    DATA_HTML_URI.test(value) ||
    EVENT_HANDLER.test(value)
  ) {
    return "must not contain HTML or script markup.";
  }
  return null;
}

/** Normalises whitespace and strips control characters (they corrupt CSV, logs and mail headers). */
export function normalizeFreeText(value: string, multiline = false): string {
  const noControls = value
    .replace(/\r\n?/g, "\n")
    // biome-ignore lint/suspicious/noControlCharactersInRegex: deliberately removing C0/C1 controls
    .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, "");
  return (multiline
    ? noControls.replace(/[ \t]{2,}/g, " ").replace(/\n{3,}/g, "\n\n")
    : noControls.replace(/\s+/g, " ")
  ).trim();
}

export type TextFieldOptions = {
  label: string;
  min: number;
  max: number;
  /** Keep newlines and cap blank-line runs instead of collapsing to one line. */
  multiline?: boolean;
};

/** A trimmed, markup-free, length-checked text field. */
export function textField(opts: TextFieldOptions) {
  return z
    .string({
      required_error: `${opts.label} is required.`,
      invalid_type_error: `${opts.label} must be text.`,
    })
    .transform((value) => normalizeFreeText(value, opts.multiline === true))
    .superRefine((value, ctx) => {
      const markup = markupIssue(value);
      if (markup) {
        ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${opts.label} ${markup}` });
        return;
      }
      if (value.length < opts.min) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: `${opts.label} must be at least ${opts.min} characters.`,
        });
      } else if (value.length > opts.max) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: `${opts.label} must be at most ${opts.max} characters.`,
        });
      }
    });
}

/** Email address: trimmed, lower-cased, length-capped and structurally validated. */
export const emailField = z
  .string({
    required_error: "Email is required.",
    invalid_type_error: "Email must be text.",
  })
  .trim()
  .toLowerCase()
  .max(254, "Email address is too long.")
  .refine((v) => /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/.test(v), "Enter a valid email address.");

/** Phone: digits plus `+ - ( )` and spaces only. Empty string is allowed (treated as absent). */
export const phoneField = z
  .string({ invalid_type_error: "Phone number must be text." })
  .trim()
  .max(30, "Phone number is too long.")
  .refine(
    (v) => v === "" || /^[\d\s()+-]{7,20}$/.test(v),
    "Phone number may only contain digits and the characters + - ( ).",
  )
  .optional();

/** Numeric database id passed in a body (guards `BigInt()` from throwing on garbage). */
export function idField(label: string) {
  return z
    .string({ required_error: `${label} is required.`, invalid_type_error: `${label} is required.` })
    .regex(/^\d{1,20}$/, `${label} is required.`);
}

export const FEEDBACK_CATEGORY_ENUM = ["complaint", "suggestion", "question", "appreciation"] as const;

/** Full validation for an unauthenticated GRM submission. */
export const publicFeedbackSchema = z.object({
  trainingProviderId: idField("Training Provider"),
  category: z.enum(FEEDBACK_CATEGORY_ENUM, {
    invalid_type_error: "Choose a valid category.",
    required_error: "Choose a category.",
  }),
  subject: textField({ label: "Subject", min: 3, max: 200 }),
  description: textField({ label: "Detailed description", min: 3, max: 4000, multiline: true }),
  submitterName: textField({ label: "Your name", min: 2, max: 100 }),
  submitterEmail: emailField,
  submitterPhone: phoneField,
  region: textField({ label: "Region", min: 1, max: 100 }).optional(),
});

export type PublicFeedbackInput = z.infer<typeof publicFeedbackSchema>;

/** Body text typed by staff in a GRM reply (also flows into notification emails). */
export const feedbackReplyBodyField = textField({
  label: "Reply",
  min: 1,
  max: 5000,
  multiline: true,
});

/** Coerces blank optional strings to `undefined` so `.optional()` accepts them. */
export function blankToUndefined(value: unknown): string | undefined {
  return typeof value === "string" && value.trim() ? value : undefined;
}

/** Route params come straight off the URL — never hand them to `BigInt()` unchecked. */
export function parseIdParam(value: string | undefined): bigint | null {
  return value && /^\d{1,20}$/.test(value) ? BigInt(value) : null;
}

// The intake form is fully unauthenticated, so cap how often a single client can
// hit it. Generous enough for a real person, far too low for a scripted run.
export const publicFormLimiter = rateLimit({
  windowMs: 10 * 60 * 1000,
  max: 30,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: "Too many requests from this address. Please try again shortly." },
});

export const publicSubmitLimiter = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 10,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: "Too many submissions from this address. Please try again later." },
});
