import "server-only";

import { z } from "zod";

import {
  blogFormSchema,
  publishIssues,
  type BlogFormValues,
} from "@/features/blogs/schemas";
import {
  blogColumns,
  createRevision,
  emptyFormValues,
  normalizeValues,
  releaseSlugPath,
  writeRelations,
} from "@/features/blogs/service";
import { blogDefaultsSchema, linkSchema } from "@/features/settings/schemas";
import { Prisma, type ContentStatus } from "@/generated/prisma/client";
import { db } from "@/lib/db";
import { env } from "@/lib/env";
import { readLocalFile } from "@/lib/storage/local";
import { cleanText } from "@/lib/utils";

import {
  blogExportSchema,
  type BlogExport,
  type ExportPost,
  type ImageRef,
} from "./format";
import { createMediaMatcher } from "./media-match";

/**
 * Loads a blog export file (see `format.ts`) into the CMS. Used by the
 * "Import JSON" screen and by `npm run import:json`.
 *
 * - Categories and authors are matched by slug. Existing ones are kept as
 *   editors left them; only empty fields are filled in.
 * - Articles are matched by slug. Existing articles are skipped, or replaced
 *   when `existing` is "update".
 * - Every article goes through the editor's validation and sanitizer, and
 *   live articles get a revision, exactly as if saved from the editor.
 * - Images are never downloaded. An image with a `url` (written by
 *   `npm run export:link-images`) is already in storage: it is used as is,
 *   and added to the media library when this CMS has no record of it but has
 *   the file. Otherwise the media library is searched for the same file
 *   (year/month folder and file name, as the WordPress importer stores
 *   them). An image found neither way is left out (an update keeps the
 *   article's current image) and listed under `imagesToUpload`; images inside
 *   the text then keep their original URL.
 * - A dry run does every check and writes nothing.
 */

export type ImportOptions = {
  /** What to do with an article whose slug already exists. */
  existing: "skip" | "update";
  dryRun: boolean;
  /** The admin running the import, recorded as author of the changes. */
  userId: string | null;
};

export type ImportAction = "create" | "update" | "skip" | "fail";

export type ImportPostResult = {
  slug: string;
  title: string;
  action: ImportAction;
  status: ContentStatus | null;
  reason?: string;
  faqs: number;
  images: number;
  warnings: string[];
};

export type ImportResult = {
  dryRun: boolean;
  source: string | null;
  summary: {
    posts: number;
    create: number;
    update: number;
    skip: number;
    fail: number;
    faqs: number;
    categoriesCreated: number;
    authorsCreated: number;
    redirectsCreated: number;
    /** Images set from files already in storage. */
    imagesFromLibrary: number;
    /** Media-library records added for linked files this CMS had no record of. */
    mediaCreated: number;
    imagesToUpload: number;
    /** Linked images whose file isn't in this server's storage. */
    imagesMissing: number;
  };
  posts: ImportPostResult[];
  /** Notes about categories, authors and redirects. */
  notes: string[];
  /** Images that weren't set because the media library doesn't have them yet. */
  imagesToUpload: {
    slug: string;
    field: string;
    sourceUrl: string;
    alt: string;
  }[];
  /** Linked images whose file isn't in this server's storage. */
  imagesMissing: { slug: string; field: string; url: string }[];
  /** Slugs of live articles that changed, for refreshing the website. */
  liveSlugs: string[];
};

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

export type ParseResult =
  | { ok: true; data: BlogExport }
  | { ok: false; error: string; issues: string[] };

/** Reads and validates an export file. Accepts the raw text or parsed JSON. */
export function parseBlogExport(input: unknown): ParseResult {
  let value = input;
  if (typeof input === "string") {
    try {
      value = JSON.parse(input.replace(/^﻿/, ""));
    } catch (error) {
      return {
        ok: false,
        error: "The file isn't valid JSON.",
        issues: [error instanceof Error ? error.message : String(error)],
      };
    }
  }
  const parsed = blogExportSchema.safeParse(value);
  if (parsed.success) return { ok: true, data: parsed.data };

  const issues = parsed.error.issues.slice(0, 50).map((issue) => {
    const where = describePath(issue.path, value);
    return where ? `${where}: ${issue.message}` : issue.message;
  });
  const top = parsed.error.issues.find((issue) => issue.path.length <= 1);
  return {
    ok: false,
    error: top?.message ?? "The file doesn't match the blog export format.",
    issues,
  };
}

/** "posts[3].faqs[1].answer" → "Post “some-slug” › faqs[1].answer". */
function describePath(path: PropertyKey[], root: unknown) {
  if (path[0] === "posts" && typeof path[1] === "number") {
    const post = (root as { posts?: { slug?: unknown }[] })?.posts?.[path[1]];
    const name =
      typeof post?.slug === "string" ? `“${post.slug}”` : `#${path[1] + 1}`;
    const rest = z.core.toDotPath(path.slice(2));
    return `Post ${name}${rest ? ` › ${rest}` : ""}`;
  }
  return z.core.toDotPath(path);
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function truncate(value: string, max: number) {
  if (value.length <= max) return value;
  const cut = value.slice(0, max - 1);
  return `${cut.slice(0, Math.max(cut.lastIndexOf(" "), max / 2)).trimEnd()}…`;
}

const isHttpsUrl = (value: string) => /^https?:\/\/\S+$/i.test(value);

const ATTRIBUTE_URL = /(\s(?:src|href)=")(https?:\/\/[^"]+)(")/gi;

// ---------------------------------------------------------------------------
// Import
// ---------------------------------------------------------------------------

export async function importBlogExport(
  file: BlogExport,
  options: ImportOptions,
): Promise<ImportResult> {
  const { dryRun } = options;
  const notes: string[] = [];
  const imagesToUpload: ImportResult["imagesToUpload"] = [];
  let imagesFromLibrary = 0;

  const [media, setting] = await Promise.all([
    db.media.findMany({
      select: { url: true, filename: true, storageKey: true },
    }),
    db.setting.findUnique({ where: { key: "blogDefaults" } }),
  ]);
  const findMedia = createMediaMatcher(media);
  const defaults = blogDefaultsSchema.safeParse(setting?.value ?? {});
  const base = emptyFormValues(
    defaults.success ? defaults.data : blogDefaultsSchema.parse({}),
  );

  const isLocalStorage = env().STORAGE_DRIVER !== "s3";
  const knownUrls = new Set(media.map((row) => row.url));
  const knownKeys = new Set(media.map((row) => row.storageKey));
  /** Linked URL → whether its file is usable here. */
  const checked = new Map<string, boolean>();
  const imagesMissing: ImportResult["imagesMissing"] = [];
  let mediaCreated = 0;

  /**
   * For an image linked to a stored file: checks the file is on this server
   * and makes sure the media library lists it.
   */
  async function linkedFileReady(slug: string, field: string, ref: ImageRef) {
    const url = ref.url;
    if (!checked.has(url)) {
      let ready = true;
      if (!knownUrls.has(url)) {
        const key = url.startsWith("/uploads/")
          ? url.slice("/uploads/".length)
          : ref.file?.storageKey;
        if (isLocalStorage && url.startsWith("/uploads/")) {
          ready = Boolean(key && (await readLocalFile(key)));
        }
        if (ready && ref.file && key && !knownKeys.has(key)) {
          mediaCreated++;
          if (!dryRun) {
            await db.media.create({
              data: {
                filename: ref.file.filename,
                storageKey: key,
                url,
                mimeType: ref.file.mimeType,
                size: ref.file.size,
                width: ref.file.width ?? null,
                height: ref.file.height ?? null,
                altText: cleanText(ref.alt),
                title: cleanText(ref.title) || null,
                uploadedById: options.userId,
              },
            });
          }
          knownKeys.add(key);
          knownUrls.add(url);
        }
      }
      checked.set(url, ready);
    }
    const ready = checked.get(url)!;
    if (!ready) imagesMissing.push({ slug, field, url });
    return ready;
  }

  /** The CMS URL for an image, or null (and listed) when this CMS doesn't have it. */
  async function resolveImage(
    slug: string,
    field: string,
    ref: ImageRef | null,
  ) {
    if (!ref) return null;
    if (ref.url) {
      if (await linkedFileReady(slug, field, ref)) {
        imagesFromLibrary++;
        return ref.url;
      }
      return null;
    }
    const row = findMedia(ref.sourceUrl);
    if (row) {
      imagesFromLibrary++;
      return row.url;
    }
    imagesToUpload.push({
      slug,
      field,
      sourceUrl: ref.sourceUrl,
      alt: ref.alt,
    });
    return null;
  }

  // ---- Categories ------------------------------------------------------------
  const categoryIds = new Map<string, string>();
  let categoriesCreated = 0;
  for (const category of dedupe(
    file.categories,
    (item) => item.slug,
    notes,
    "category",
  )) {
    const existing = await db.category.findUnique({
      where: { slug: category.slug },
    });
    if (existing) {
      categoryIds.set(category.slug, existing.id);
      if (!existing.description && category.description && !dryRun) {
        await db.category.update({
          where: { id: existing.id },
          data: { description: cleanText(category.description) },
        });
      }
      continue;
    }
    categoriesCreated++;
    notes.push(
      `Category “${category.name}” (${category.slug}) ${dryRun ? "would be" : "was"} created.`,
    );
    if (dryRun) {
      categoryIds.set(category.slug, `new:${category.slug}`);
      continue;
    }
    const created = await db.category.create({
      data: {
        name: cleanText(category.name),
        slug: category.slug,
        description: cleanText(category.description) || null,
        status: category.status,
      },
    });
    categoryIds.set(category.slug, created.id);
  }

  // ---- Authors ---------------------------------------------------------------
  const authorIds = new Map<string, string>();
  let authorsCreated = 0;
  for (const author of dedupe(
    file.authors,
    (item) => item.slug,
    notes,
    "author",
  )) {
    const existing = await db.author.findUnique({
      where: { slug: author.slug },
    });
    const image = existing?.profileImage
      ? null
      : await resolveImage(
          `author:${author.slug}`,
          "profileImage",
          author.profileImage,
        );
    if (existing) {
      authorIds.set(author.slug, existing.id);
      // Only fill gaps: never overwrite what editors wrote in the CMS.
      const fill = {
        ...(!existing.role && author.role && { role: cleanText(author.role) }),
        ...(!existing.bio && author.bio && { bio: author.bio.trim() }),
        ...(image && { profileImage: image }),
      };
      if (Object.keys(fill).length && !dryRun) {
        await db.author.update({ where: { id: existing.id }, data: fill });
      }
      continue;
    }
    authorsCreated++;
    notes.push(
      `Author “${author.name}” (${author.slug}) ${dryRun ? "would be" : "was"} created.`,
    );
    if (dryRun) {
      authorIds.set(author.slug, `new:${author.slug}`);
      continue;
    }
    const created = await db.author.create({
      data: {
        name: cleanText(author.name),
        slug: author.slug,
        role: cleanText(author.role) || null,
        bio: author.bio.trim() || null,
        profileImage: image,
        status: author.status,
      },
    });
    authorIds.set(author.slug, created.id);
  }

  /** Categories and authors the file uses without listing them may already exist. */
  async function lookup(
    map: Map<string, string>,
    slug: string | null,
    find: (slug: string) => Promise<{ id: string } | null>,
  ) {
    if (!slug) return { id: null, missing: false };
    if (!map.has(slug)) {
      const row = await find(slug);
      if (!row) return { id: null, missing: true };
      map.set(slug, row.id);
    }
    return { id: map.get(slug)!, missing: false };
  }

  // ---- Articles --------------------------------------------------------------
  const results: ImportPostResult[] = [];
  const liveSlugs: string[] = [];
  /** Slug → ID of every article written, for related articles. */
  const writtenIds = new Map<string, string>();
  const manualRelated: {
    slug: string;
    related: string[];
    result: ImportPostResult;
  }[] = [];
  const seenSlugs = new Set<string>();

  for (const post of file.posts) {
    const warnings: string[] = [];
    const result: ImportPostResult = {
      slug: post.slug,
      title: post.title,
      action: "fail",
      status: null,
      faqs: post.faqs.length,
      images: post.images.length,
      warnings,
    };
    results.push(result);

    try {
      if (seenSlugs.has(post.slug)) {
        result.reason = "Another post earlier in the file has the same slug.";
        continue;
      }
      seenSlugs.add(post.slug);

      const existing = await db.blog.findUnique({
        where: { slug: post.slug },
        select: {
          id: true,
          status: true,
          featuredImage: true,
          featuredImageAlt: true,
          featuredImageTitle: true,
          ogImage: true,
          ctaImage: true,
        },
      });
      if (existing && options.existing === "skip") {
        result.action = "skip";
        result.status = existing.status;
        result.reason = "Already in the CMS.";
        writtenIds.set(post.slug, existing.id);
        continue;
      }

      const category = await lookup(categoryIds, post.category, (slug) =>
        db.category.findUnique({ where: { slug }, select: { id: true } }),
      );
      if (category.missing)
        warnings.push(
          `Category “${post.category}” isn't in the file or the CMS; left empty.`,
        );
      const author = await lookup(authorIds, post.author, (slug) =>
        db.author.findUnique({ where: { slug }, select: { id: true } }),
      );
      if (author.missing)
        warnings.push(
          `Author “${post.author}” isn't in the file or the CMS; left empty.`,
        );

      // Images inside the text that point at a stored file: if this server
      // doesn't have the file, fall back to the original URL.
      let content = post.content;
      for (const ref of post.images) {
        if (!ref.url) continue;
        if (await linkedFileReady(post.slug, "content", ref)) {
          imagesFromLibrary++;
        } else {
          content = content.split(`"${ref.url}"`).join(`"${ref.sourceUrl}"`);
        }
      }

      const { values, status, publishedAt, contentUpdatedAt } = buildValues(
        { ...post, content },
        {
          base,
          warnings,
          categoryId: category.id,
          authorId: author.id,
          existing,
          images: {
            featured: await resolveImage(
              post.slug,
              "featuredImage",
              post.featuredImage,
            ),
            og: await resolveImage(post.slug, "ogImage", post.seo.ogImage),
            cta: post.cta
              ? await resolveImage(post.slug, "ctaImage", post.cta.image)
              : null,
          },
          findMedia: (sourceUrl) => findMedia(sourceUrl)?.url ?? null,
          countLibraryImage: () => imagesFromLibrary++,
        },
      );

      const parsed = blogFormSchema.safeParse(values);
      if (!parsed.success) {
        result.reason = parsed.error.issues
          .slice(0, 5)
          .map((issue) => `${z.core.toDotPath(issue.path)}: ${issue.message}`)
          .join("; ");
        continue;
      }
      const clean = normalizeValues(parsed.data);

      let finalStatus = status;
      if (status !== "DRAFT") {
        const issues = Object.values(publishIssues(clean));
        if (issues.length) {
          warnings.push(`Imported as a draft: ${issues[0]}`);
          finalStatus = "DRAFT";
        }
      }
      result.status = finalStatus;
      result.faqs = clean.faqs.length;

      if (post.related.mode === "MANUAL" && post.related.slugs.length) {
        manualRelated.push({
          slug: post.slug,
          related: post.related.slugs,
          result,
        });
      }

      if (dryRun) {
        result.action = existing ? "update" : "create";
        writtenIds.set(post.slug, existing?.id ?? `new:${post.slug}`);
        continue;
      }

      const data = {
        ...blogColumns(clean),
        status: finalStatus,
        publishedAt: finalStatus === "DRAFT" ? null : publishedAt,
        scheduledAt: finalStatus === "SCHEDULED" ? publishedAt : null,
        contentUpdatedAt: finalStatus === "PUBLISHED" ? contentUpdatedAt : null,
        autosave: Prisma.DbNull,
        autosavedAt: null,
        updatedById: options.userId,
      };

      const id = await db.$transaction(async (tx) => {
        let blogId: string;
        if (existing) {
          await tx.blog.update({
            where: { id: existing.id },
            data: { ...data, version: { increment: 1 } },
          });
          blogId = existing.id;
        } else {
          const created = await tx.blog.create({
            data: {
              ...(data as Prisma.BlogUncheckedCreateInput),
              createdById: options.userId,
              // Keeps "Newest" sorting in publishing order.
              ...(publishedAt && { createdAt: publishedAt }),
            },
            select: { id: true },
          });
          blogId = created.id;
        }
        await writeRelations(tx, blogId, clean);
        if (finalStatus !== "DRAFT") {
          await releaseSlugPath(tx, clean.slug);
          await createRevision(
            tx,
            blogId,
            clean,
            existing ? "updated" : "published",
            options.userId,
          );
        }
        return blogId;
      });
      writtenIds.set(post.slug, id);
      result.action = existing ? "update" : "create";
      // A live article that became a draft must leave the website too.
      if (
        finalStatus !== "DRAFT" ||
        (existing && existing.status !== "DRAFT")
      ) {
        liveSlugs.push(post.slug);
      }
    } catch (error) {
      result.action = "fail";
      result.reason = error instanceof Error ? error.message : String(error);
    }
  }

  // ---- Related articles (needs every article's ID) ------------------------
  for (const { slug, related, result } of manualRelated) {
    if (result.action === "fail" || result.action === "skip") continue;
    const ids: string[] = [];
    for (const relatedSlug of related) {
      if (relatedSlug === slug) continue;
      let id = writtenIds.get(relatedSlug);
      if (!id) {
        id = (
          await db.blog.findUnique({
            where: { slug: relatedSlug },
            select: { id: true },
          })
        )?.id;
      }
      if (id) ids.push(id);
      else
        result.warnings.push(
          `Related article “${relatedSlug}” wasn't found; left out.`,
        );
    }
    const picked = [...new Set(ids)].slice(0, 3);
    if (related.length > 3)
      result.warnings.push("Only the first 3 related articles are kept.");
    const blogId = writtenIds.get(slug);
    if (dryRun || !blogId) continue;
    await db.$transaction(async (tx) => {
      await tx.relatedBlog.deleteMany({ where: { blogId } });
      if (picked.length) {
        await tx.relatedBlog.createMany({
          data: picked.map((relatedBlogId, position) => ({
            blogId,
            relatedBlogId,
            position,
          })),
        });
      }
    });
  }

  // ---- Redirects -------------------------------------------------------------
  let redirectsCreated = 0;
  for (const redirect of file.redirects) {
    // A redirect must never hide an article that lives at that path.
    const articleSlug = /^\/blog\/([^/]+)\/$/.exec(redirect.fromPath)?.[1];
    const shadowsArticle =
      articleSlug &&
      (seenSlugs.has(articleSlug) ||
        (await db.blog.findUnique({
          where: { slug: articleSlug },
          select: { id: true },
        })));
    if (shadowsArticle) {
      notes.push(
        `Redirect from ${redirect.fromPath} skipped: an article lives at that path.`,
      );
      continue;
    }
    const existing = await db.redirect.findUnique({
      where: { fromPath: redirect.fromPath },
    });
    if (
      existing &&
      (options.existing === "skip" || existing.toPath === redirect.toPath)
    )
      continue;
    redirectsCreated++;
    if (dryRun) continue;
    await db.redirect.upsert({
      where: { fromPath: redirect.fromPath },
      create: {
        fromPath: redirect.fromPath,
        toPath: redirect.toPath,
        permanent: redirect.permanent,
      },
      update: { toPath: redirect.toPath, permanent: redirect.permanent },
    });
  }

  const count = (action: ImportAction) =>
    results.filter((post) => post.action === action).length;
  return {
    dryRun,
    source: file.source ?? null,
    summary: {
      posts: results.length,
      create: count("create"),
      update: count("update"),
      skip: count("skip"),
      fail: count("fail"),
      faqs: results
        .filter((post) => post.action === "create" || post.action === "update")
        .reduce((total, post) => total + post.faqs, 0),
      categoriesCreated,
      authorsCreated,
      redirectsCreated,
      imagesFromLibrary,
      mediaCreated,
      imagesToUpload: imagesToUpload.length,
      imagesMissing: imagesMissing.length,
    },
    posts: results,
    notes,
    imagesToUpload,
    imagesMissing,
    liveSlugs,
  };
}

function dedupe<T>(
  items: T[],
  key: (item: T) => string,
  notes: string[],
  noun: string,
) {
  const seen = new Set<string>();
  return items.filter((item) => {
    const value = key(item);
    if (seen.has(value)) {
      notes.push(
        `The ${noun} “${value}” is listed twice; the first entry was used.`,
      );
      return false;
    }
    seen.add(value);
    return true;
  });
}

// ---------------------------------------------------------------------------
// Post → editor values
// ---------------------------------------------------------------------------

type BuildContext = {
  base: BlogFormValues;
  warnings: string[];
  categoryId: string | null;
  authorId: string | null;
  existing: {
    featuredImage: string | null;
    featuredImageAlt: string | null;
    featuredImageTitle: string | null;
    ogImage: string | null;
    ctaImage: string | null;
  } | null;
  /** Featured, share and CTA images, already resolved to CMS URLs. */
  images: { featured: string | null; og: string | null; cta: string | null };
  findMedia: (sourceUrl: string) => string | null;
  countLibraryImage: () => void;
};

function buildValues(post: ExportPost, context: BuildContext) {
  const { base, warnings, existing } = context;
  const title = cleanText(post.title);
  const now = new Date();

  // ---- Status and dates
  let status: ContentStatus = post.status;
  let publishedAt = post.publishedAt ? new Date(post.publishedAt) : null;
  if (status === "SCHEDULED" && !publishedAt) {
    warnings.push("Scheduled without a date; imported as a draft.");
    status = "DRAFT";
  }
  if (status === "PUBLISHED" && !publishedAt) {
    warnings.push("Published without a date; the import time is used.");
    publishedAt = now;
  }
  if (status === "PUBLISHED" && publishedAt && publishedAt > now) {
    warnings.push("Published with a future date; imported as scheduled.");
    status = "SCHEDULED";
  }
  const updated = post.updatedAt ? new Date(post.updatedAt) : null;
  const contentUpdatedAt =
    publishedAt && updated && updated.getTime() - publishedAt.getTime() > 60_000
      ? updated
      : null;

  // ---- Images inside the text still at their original URL: library copies when they exist
  const content = post.content.replace(
    ATTRIBUTE_URL,
    (whole, before: string, url: string, after: string) => {
      const decoded = url.replace(/&amp;/g, "&");
      if (
        !/\/wp-content\/uploads\//.test(decoded) &&
        !/\.(avif|gif|jpe?g|png|svg|webp)$/i.test(decoded)
      ) {
        return whole;
      }
      const library = context.findMedia(decoded);
      if (!library) return whole;
      context.countLibraryImage();
      return `${before}${library}${after}`;
    },
  );

  const { featured, og, cta: ctaImage } = context.images;

  // ---- SEO, shortened to the editor's limits
  const seoTitle = cleanText(post.seo.title);
  if (seoTitle.length > 120)
    warnings.push(
      "The SEO title is over 120 characters, so the article title is used.",
    );
  const metaDescription = cleanText(post.seo.metaDescription);
  if (metaDescription.length > 320)
    warnings.push("The meta description was shortened to 320 characters.");
  const canonical = post.seo.canonicalUrl.trim();
  if (canonical && !isHttpsUrl(canonical))
    warnings.push(`Canonical URL “${canonical}” isn't a full URL; left empty.`);
  const excerpt = cleanText(post.excerpt) || metaDescription;
  if (excerpt.length > 500)
    warnings.push("The excerpt was shortened to 500 characters.");

  // ---- Call to action: the file's, or the Blog defaults
  let cta = {
    ctaEnabled: base.ctaEnabled,
    ctaTitle: base.ctaTitle,
    ctaDescription: base.ctaDescription,
    ctaButtonText: base.ctaButtonText,
    ctaButtonUrl: base.ctaButtonUrl,
    ctaImage: base.ctaImage,
  };
  if (post.cta) {
    const buttonUrl = post.cta.buttonUrl.trim();
    const urlOk = linkSchema.safeParse(buttonUrl).success;
    if (!urlOk)
      warnings.push(
        `CTA button URL “${buttonUrl}” isn't valid; the CTA is turned off.`,
      );
    cta = {
      ctaEnabled: post.cta.enabled && urlOk,
      ctaTitle: truncate(cleanText(post.cta.title), 120),
      ctaDescription: truncate(cleanText(post.cta.description), 300),
      ctaButtonText: truncate(cleanText(post.cta.buttonText), 40),
      ctaButtonUrl: urlOk ? buttonUrl : "",
      ctaImage: ctaImage ?? existing?.ctaImage ?? "",
    };
  }

  const values: BlogFormValues = {
    ...base,
    title,
    slug: post.slug,
    excerpt: truncate(excerpt, 500),
    content,
    featuredImage: featured ?? existing?.featuredImage ?? "",
    featuredImageAlt: truncate(
      cleanText(post.featuredImage?.alt ?? "") ||
        existing?.featuredImageAlt ||
        (post.featuredImage ? title : ""),
      300,
    ),
    featuredImageTitle: truncate(
      cleanText(post.featuredImage?.title ?? "") ||
        existing?.featuredImageTitle ||
        "",
      200,
    ),
    categoryId: context.categoryId,
    authorId: context.authorId,
    tags: post.tags,
    publishedAt:
      status === "DRAFT" ? null : (publishedAt?.toISOString() ?? null),
    seoTitle:
      seoTitle && seoTitle !== title && seoTitle.length <= 120 ? seoTitle : "",
    metaDescription: truncate(metaDescription, 320),
    canonicalUrl: isHttpsUrl(canonical) ? canonical : "",
    focusKeyword: truncate(cleanText(post.seo.focusKeyword), 100),
    ogTitle: truncate(cleanText(post.seo.ogTitle), 120),
    ogDescription: truncate(cleanText(post.seo.ogDescription), 320),
    ogImage: og ?? existing?.ogImage ?? "",
    robotsIndex: post.seo.robotsIndex,
    robotsFollow: post.seo.robotsFollow,
    faqs: post.faqs.map((faq, index) => ({
      id: `import-${index + 1}`,
      ...faq,
    })),
    faqSchemaEnabled: post.faqSchemaEnabled,
    ...cta,
    relatedMode: post.related.mode,
    // Filled in after every article is written.
    relatedBlogIds: [],
  };

  return { values, status, publishedAt, contentUpdatedAt };
}
