import { z } from "zod";

export const REDIRECT_PATH_MAX = 500;
export const REDIRECT_DESTINATION_MAX = 1000;

/** Collapses repeated slashes and adds the trailing slash the website uses. */
function withTrailingSlash(path: string) {
  const collapsed = path.replace(/\/{2,}/g, "/");
  return collapsed.endsWith("/") ? collapsed : `${collapsed}/`;
}

/** "/Old-Page" becomes "/old-page/". Call on input that passed `sourcePathSchema`. */
export function normalizeSourcePath(value: string) {
  return withTrailingSlash(value.trim().toLowerCase());
}

/**
 * Root-relative paths are lowercased and get a trailing slash, keeping any
 * query or fragment; absolute URLs are kept as typed.
 */
export function normalizeDestination(value: string) {
  const trimmed = value.trim();
  if (!trimmed.startsWith("/")) return trimmed;
  const split = trimmed.search(/[?#]/);
  const path = split === -1 ? trimmed : trimmed.slice(0, split);
  const suffix = split === -1 ? "" : trimmed.slice(split);
  return `${withTrailingSlash(path.toLowerCase())}${suffix}`;
}

export const isAbsoluteDestination = (value: string) =>
  /^https:\/\//i.test(value);

const sourcePathSchema = z
  .string()
  .trim()
  .min(1, "Enter the old path.")
  .max(REDIRECT_PATH_MAX, `Paths can be up to ${REDIRECT_PATH_MAX} characters.`)
  .refine(
    (value) => !/^[a-z][a-z0-9+.-]*:/i.test(value) && !value.startsWith("//"),
    "Enter a path on this site, not a full URL. For example /old-page/.",
  )
  .refine((value) => value.startsWith("/"), "Start the path with /.")
  .refine(
    (value) => !/[\s?#]/.test(value),
    "Use a path without spaces, ? or #.",
  )
  .transform(normalizeSourcePath)
  .refine((value) => value !== "/", "The homepage can't be redirected.");

const destinationSchema = z
  .string()
  .trim()
  .min(1, "Enter where visitors should go.")
  .max(
    REDIRECT_DESTINATION_MAX,
    `Destinations can be up to ${REDIRECT_DESTINATION_MAX} characters.`,
  )
  .refine((value) => {
    if (value.startsWith("/")) {
      return !value.startsWith("//") && !/\s/.test(value);
    }
    try {
      const url = new URL(value);
      return (
        url.protocol === "https:" && Boolean(url.hostname) && !/\s/.test(value)
      );
    } catch {
      return false;
    }
  }, "Use a path starting with / or a full https:// URL.")
  .transform(normalizeDestination);

/** The "Add redirect" form. Paths come back normalized. */
export const redirectFormSchema = z.object({
  fromPath: sourcePathSchema,
  toPath: destinationSchema,
  permanent: z.boolean(),
});

export type RedirectFormInput = z.input<typeof redirectFormSchema>;
export type RedirectFormValues = z.output<typeof redirectFormSchema>;
