import { z } from "zod";

import { SLUG_MAX_LENGTH, SLUG_PATTERN } from "@/lib/slug";

export const AUTHOR_NAME_MAX = 80;
export const AUTHOR_ROLE_MAX = 80;
export const AUTHOR_BIO_MAX = 1000;

/** Optional text: trimmed, and stored as null when empty. */
const optionalText = (max: number) =>
  z
    .string()
    .trim()
    .max(max, `Use at most ${max} characters.`)
    .nullish()
    .transform((value) => value || null);

/** What the author dialog sends to `createAuthor` and `updateAuthor`. */
export const authorInputSchema = z.object({
  name: z
    .string()
    .trim()
    .min(1, "Enter the author's name.")
    .max(AUTHOR_NAME_MAX, `Use at most ${AUTHOR_NAME_MAX} characters.`),
  slug: z
    .string()
    .trim()
    .min(1, "Enter a slug.")
    .max(SLUG_MAX_LENGTH, `Slugs can be up to ${SLUG_MAX_LENGTH} characters.`)
    .regex(SLUG_PATTERN, "Use lowercase letters, numbers and single hyphens."),
  /** Job title shown in the byline. */
  role: optionalText(AUTHOR_ROLE_MAX),
  bio: optionalText(AUTHOR_BIO_MAX),
  /** A root-relative upload path or an http(s) URL, as the media library stores them. */
  profileImage: z
    .string()
    .trim()
    .max(1000)
    .refine(
      (value) =>
        value === "" ||
        /^\/uploads\/\S+$/.test(value) ||
        /^https?:\/\/\S+$/i.test(value),
      "Choose an image from the media library.",
    )
    .nullish()
    .transform((value) => value || null),
  status: z.enum(["ACTIVE", "INACTIVE"], "Choose a status."),
});

export type AuthorInput = z.input<typeof authorInputSchema>;
