import { z } from "zod";

import {
  AUTHOR_BIO_MAX,
  AUTHOR_NAME_MAX,
  AUTHOR_ROLE_MAX,
} from "@/features/authors/schemas";
import { MAX_FAQS, MAX_TAGS } from "@/features/blogs/schemas";
import {
  CATEGORY_DESCRIPTION_MAX,
  CATEGORY_NAME_MAX,
} from "@/features/categories/schemas";
import { redirectFormSchema } from "@/features/redirects/schemas";
import { SLUG_MAX_LENGTH, SLUG_PATTERN } from "@/lib/slug";

/**
 * The blog export file: every category, author and article of a blog in one
 * JSON document. The "Import JSON" screen checks a file against this schema,
 * then the Laravel CMS imports it (docs/laravel-blog-api.md §8.7). Also used
 * by `npm run laravel -- import <file>`.
 *
 * Records point at each other by slug, never by database ID, so the file can
 * be loaded into any CMS.
 *
 * Images are references only ({ sourceUrl, alt, title }). The importer never
 * downloads them: images inside `content` keep their URL, and featured, share
 * and profile images are only filled in when the media library already holds
 * a file with the same name.
 *
 * Optional fields may be left out of a hand-written file; defaults apply.
 * Keep docs/blog-export-format.md in step with this file.
 */

export const BLOG_EXPORT_FORMAT = "secondline-blog-export";
export const BLOG_EXPORT_VERSION = 1;

/**
 * Largest file the admin screen takes. Server Actions accept 4 MB bodies
 * (next.config.ts); a 50-article export is about 0.6 MB. Bigger files go
 * through `npm run laravel -- import <file>`.
 */
export const IMPORT_MAX_CHARS = 3_500_000;

const slug = z
  .string()
  .trim()
  .min(1, "Missing slug.")
  .max(SLUG_MAX_LENGTH, `Slugs can be up to ${SLUG_MAX_LENGTH} characters.`)
  .regex(SLUG_PATTERN, "Use lowercase letters, numbers and single hyphens.");

const text = (max: number) =>
  z
    .string()
    .max(max, `Keep this under ${max} characters.`)
    .nullish()
    .transform((value) => value ?? "");

const isoDate = z.iso
  .datetime({ offset: true })
  .nullish()
  .transform((value) => value ?? null);

/** The media-library record of an image already stored in the CMS. */
export const mediaFileSchema = z.object({
  /** Location in storage, e.g. "2026/05/banner.png" (local: under storage/uploads/). */
  storageKey: z
    .string()
    .min(1)
    .max(500)
    .refine(
      (value) => !value.startsWith("/") && !value.split("/").includes(".."),
      "Use a relative storage key.",
    ),
  filename: z.string().min(1).max(255),
  mimeType: z.string().regex(/^image\//, "Only images can be imported."),
  size: z.number().int().nonnegative(),
  width: z.number().int().positive().nullish(),
  height: z.number().int().positive().nullish(),
});

/**
 * An image. `sourceUrl` is where it came from and is never downloaded. When
 * `url` is set (by `npm run export:link-images`), the image is already in
 * the CMS's storage at that address, and `file` describes it so an empty CMS
 * can add it to its media library.
 */
export const imageRefSchema = z.object({
  sourceUrl: z.url({ protocol: /^https?$/ }).max(1000),
  alt: text(300),
  title: text(200),
  url: z
    .string()
    .trim()
    .max(1000)
    .refine(
      (value) =>
        value === "" ||
        /^\/uploads\/\S+$/.test(value) ||
        /^https?:\/\/\S+$/i.test(value),
      "Use an /uploads/… path or a full URL.",
    )
    .nullish()
    .transform((value) => value ?? ""),
  file: mediaFileSchema.nullish().transform((value) => value ?? null),
});

export const exportCategorySchema = z.object({
  slug,
  name: z.string().trim().min(1).max(CATEGORY_NAME_MAX),
  description: text(CATEGORY_DESCRIPTION_MAX),
  status: z.enum(["ACTIVE", "INACTIVE"]).default("ACTIVE"),
});

export const exportAuthorSchema = z.object({
  slug,
  name: z.string().trim().min(1).max(AUTHOR_NAME_MAX),
  role: text(AUTHOR_ROLE_MAX),
  bio: text(AUTHOR_BIO_MAX),
  profileImage: imageRefSchema.nullish().transform((value) => value ?? null),
  status: z.enum(["ACTIVE", "INACTIVE"]).default("ACTIVE"),
});

export const exportPostSchema = z.object({
  slug,
  title: z.string().trim().min(1, "Missing title."),
  excerpt: text(2000),
  /** Article HTML. Sanitized again on import, like editor output. */
  content: z.string().default(""),
  status: z.enum(["PUBLISHED", "SCHEDULED", "DRAFT"]).default("DRAFT"),
  /** When the article went live (or goes live, when scheduled). */
  publishedAt: isoDate,
  /** Last meaningful change after publishing, shown as "Updated" on the site. */
  updatedAt: isoDate,
  /** Category slug. */
  category: slug.nullish().transform((value) => value ?? null),
  /** Author slug. */
  author: slug.nullish().transform((value) => value ?? null),
  tags: z.array(z.string().trim().min(1).max(40)).max(MAX_TAGS).default([]),

  featuredImage: imageRefSchema.nullish().transform((value) => value ?? null),

  seo: z
    .object({
      title: text(500),
      metaDescription: text(1000),
      canonicalUrl: text(500),
      focusKeyword: text(100),
      ogTitle: text(500),
      ogDescription: text(1000),
      ogImage: imageRefSchema.nullish().transform((value) => value ?? null),
      robotsIndex: z.boolean().default(true),
      robotsFollow: z.boolean().default(true),
    })
    .prefault({}),

  faqs: z
    .array(
      z.object({
        question: z.string().trim().min(1).max(300),
        answer: z.string().trim().min(1).max(5000),
      }),
    )
    .max(MAX_FAQS)
    .default([]),
  faqSchemaEnabled: z.boolean().default(true),

  /** Left out or null: the "Blog defaults" from Settings apply, as for a new article. */
  cta: z
    .object({
      enabled: z.boolean().default(false),
      title: text(120),
      description: text(300),
      buttonText: text(40),
      buttonUrl: text(500),
      image: imageRefSchema.nullish().transform((value) => value ?? null),
    })
    .nullish()
    .transform((value) => value ?? null),

  related: z
    .object({
      mode: z.enum(["AUTOMATIC", "MANUAL"]).default("AUTOMATIC"),
      /** Slugs of other articles, in display order (MANUAL only). */
      slugs: z.array(slug).max(10).default([]),
    })
    .prefault({}),

  /** Every image inside `content`, for re-uploading later. Informational. */
  images: z.array(imageRefSchema).default([]),

  /** Where the article came from. Informational. */
  legacy: z
    .object({
      id: z.union([z.string(), z.number()]).optional(),
      url: z.string().optional(),
      status: z.string().optional(),
    })
    .nullish(),

  /** Notes from the exporter, e.g. content it had to change. Informational. */
  warnings: z.array(z.string()).default([]),
});

export const blogExportSchema = z.object({
  format: z.literal(BLOG_EXPORT_FORMAT, {
    error: `This isn't a blog export file (expected "format": "${BLOG_EXPORT_FORMAT}").`,
  }),
  version: z.literal(BLOG_EXPORT_VERSION, {
    error: `Only version ${BLOG_EXPORT_VERSION} export files can be imported.`,
  }),
  source: z.string().optional(),
  exportedAt: z.string().optional(),
  categories: z.array(exportCategorySchema).default([]),
  authors: z.array(exportAuthorSchema).default([]),
  posts: z.array(exportPostSchema).min(1, "The file has no posts."),
  /** Old article paths that should forward somewhere, e.g. "/blog/old-slug/". */
  redirects: z
    .array(redirectFormSchema.extend({ permanent: z.boolean().default(true) }))
    .default([]),
});

export type ImageRef = z.output<typeof imageRefSchema>;
export type ExportCategory = z.output<typeof exportCategorySchema>;
export type ExportAuthor = z.output<typeof exportAuthorSchema>;
export type ExportPost = z.output<typeof exportPostSchema>;
export type BlogExport = z.output<typeof blogExportSchema>;
/** What the exporter writes (optional fields may be omitted by hand-written files). */
export type BlogExportInput = z.input<typeof blogExportSchema>;
