"use server";

import { revalidatePath } from "next/cache";
import { z } from "zod";

import { Prisma } from "@/generated/prisma/client";
import { ActionError, runAction, type ActionResult } from "@/lib/actions";
import { requireActionAdmin } from "@/lib/auth/guards";
import { db } from "@/lib/db";
import { automaticRelated } from "@/features/public-api/queries";
import { revalidateSite } from "@/lib/site";
import { slugify, uniqueSlug } from "@/lib/slug";

import { MARKDOWN_MAX_CHARS, parseBlogMarkdown, type MarkdownImportResult } from "./markdown-import";
import {
  blogFormSchema,
  publishIssues,
  saveIntents,
  type BlogFormValues,
  type SaveBlogResult,
} from "./schemas";
import {
  blogColumns,
  blogEditorInclude,
  createRevision,
  normalizeValues,
  parseSnapshot,
  recordSlugChange,
  releaseSlugPath,
  resolveReferences,
  toEditorMeta,
  toFormValues,
  writeRelations,
} from "./service";

const idSchema = z.string().min(1).max(64);

/** A minute of slack, so "publish now" with the current time never counts as the future. */
const FUTURE_TOLERANCE_MS = 60 * 1000;

const saveInputSchema = z.object({
  id: idSchema.nullable(),
  version: z.number().int().nullable(),
  intent: z.enum(saveIntents),
  values: blogFormSchema,
});

function conflictError() {
  return new ActionError(
    "Someone else changed this article since you opened it. Reload to get the latest version; copy any text you want to keep first.",
    409,
    undefined,
    true,
  );
}

async function isSlugTaken(slug: string, exceptId: string | null) {
  const match = await db.blog.findFirst({
    where: { slug, ...(exceptId && { NOT: { id: exceptId } }) },
    select: { title: true },
  });
  return match;
}

function revalidateAdmin(id?: string) {
  revalidatePath("/admin");
  revalidatePath("/admin/blogs");
  revalidatePath("/admin/seo");
  if (id) revalidatePath(`/admin/blogs/${id}`);
}

/**
 * Saves the editor. `intent` decides what happens to the article's status:
 *
 * - autosave: drafts are saved in place. Live and scheduled articles keep
 *   their public version; the edits are parked in `autosave` until Update.
 * - draft: saves a draft.
 * - publish / schedule: validates, then goes live now or at `publishedAt`.
 * - update: applies edits to a live or scheduled article and records a revision.
 * - unpublish: takes the article offline as a draft.
 */
export async function saveBlog(input: {
  id: string | null;
  version: number | null;
  intent: (typeof saveIntents)[number];
  values: BlogFormValues;
}): Promise<ActionResult<SaveBlogResult>> {
  return runAction(async () => {
    const admin = await requireActionAdmin();
    const parsed = saveInputSchema.parse(input);
    const { intent } = parsed;
    const now = new Date();

    const existing = parsed.id
      ? await db.blog.findUnique({ where: { id: parsed.id }, include: blogEditorInclude })
      : null;
    if (parsed.id && !existing) {
      throw new ActionError("This article no longer exists. It may have been deleted.", 404);
    }
    if (existing && parsed.version !== null && existing.version !== parsed.version) {
      throw conflictError();
    }

    let values = await resolveReferences(normalizeValues(parsed.values), existing?.id ?? null);
    const status = existing?.status ?? "DRAFT";
    const isLive = status !== "DRAFT";

    // Nothing to save yet: a brand-new article the author hasn't typed into.
    if (!existing && intent === "autosave" && !values.title && !values.content) {
      throw new ActionError("Nothing to save yet.");
    }

    // ---- Autosave of a live or scheduled article: park the edits ----------
    if (intent === "autosave" && existing && isLive) {
      const { count } = await db.blog.updateMany({
        where: { id: existing.id, version: existing.version },
        data: {
          autosave: values as unknown as Prisma.InputJsonValue,
          autosavedAt: now,
        },
      });
      if (count === 0) throw conflictError();
      return {
        ok: true,
        data: {
          blog: {
            ...toEditorMeta(existing),
            autosavedAt: now.toISOString(),
          },
          values,
        },
      };
    }

    // ---- Slug ---------------------------------------------------------------
    const goingLive = intent === "publish" || intent === "schedule";
    if (!values.slug) {
      values = { ...values, slug: slugify(values.title) };
    }
    if (!values.slug && !goingLive) {
      values = { ...values, slug: `untitled-${Date.now().toString(36)}` };
    }
    if (values.slug) {
      const taken = await isSlugTaken(values.slug, existing?.id ?? null);
      if (taken) {
        // Drafts quietly get a free variant; anything going live must be deliberate.
        if (!isLive && (intent === "autosave" || intent === "draft")) {
          const slug = await uniqueSlug(values.slug, async (candidate) =>
            Boolean(await isSlugTaken(candidate, existing?.id ?? null)),
          );
          values = { ...values, slug };
        } else {
          throw new ActionError(
            `This URL is already used by “${taken.title}”.`,
            409,
            { slug: `Already used by “${taken.title}”. Choose another slug.` },
          );
        }
      }
    }

    // ---- Status and dates ---------------------------------------------------
    const chosenDate = values.publishedAt ? new Date(values.publishedAt) : null;
    const isFuture = (date: Date | null) =>
      Boolean(date && date.getTime() > now.getTime() + FUTURE_TOLERANCE_MS);

    const requireLiveReady = () => {
      const issues = publishIssues(values);
      if (Object.keys(issues).length) {
        throw new ActionError(Object.values(issues)[0], 400, issues);
      }
    };

    let data: Prisma.BlogUncheckedUpdateInput = blogColumns(values);
    let revisionReason: "published" | "updated" | "unpublished" | null = null;
    let affectsSite = false;

    switch (intent) {
      case "autosave":
      case "draft": {
        if (isLive) {
          throw new ActionError(
            "This article is live. Use Update to save changes, or Unpublish to turn it back into a draft.",
          );
        }
        data = { ...data, status: "DRAFT", publishedAt: chosenDate };
        break;
      }
      case "publish": {
        if (status === "PUBLISHED") {
          throw new ActionError("This article is already published. Use Update to save changes.");
        }
        requireLiveReady();
        if (isFuture(chosenDate)) {
          throw new ActionError("The publish date is in the future. Use Schedule instead.", 400, {
            publishedAt: "In the future: schedule the article instead.",
          });
        }
        data = {
          ...data,
          status: "PUBLISHED",
          publishedAt: chosenDate ?? now,
          scheduledAt: null,
          autosave: Prisma.DbNull,
          autosavedAt: null,
        };
        revisionReason = "published";
        affectsSite = true;
        break;
      }
      case "schedule": {
        requireLiveReady();
        if (!chosenDate || !isFuture(chosenDate)) {
          throw new ActionError("Pick a future date and time to schedule.", 400, {
            publishedAt: "Pick a date and time in the future.",
          });
        }
        if (status === "PUBLISHED") {
          throw new ActionError("This article is already live. Unpublish it before scheduling.");
        }
        data = {
          ...data,
          status: "SCHEDULED",
          publishedAt: chosenDate,
          scheduledAt: chosenDate,
          autosave: Prisma.DbNull,
          autosavedAt: null,
        };
        affectsSite = true;
        break;
      }
      case "update": {
        if (!existing || !isLive) {
          throw new ActionError("This article isn't live yet. Save it as a draft or publish it.");
        }
        requireLiveReady();
        if (status === "SCHEDULED") {
          if (!chosenDate || !isFuture(chosenDate)) {
            throw new ActionError(
              "Scheduled articles need a future date. Pick a new time, or publish now.",
              400,
              { publishedAt: "Pick a date and time in the future." },
            );
          }
          data = { ...data, publishedAt: chosenDate, scheduledAt: chosenDate };
        } else {
          if (isFuture(chosenDate)) {
            throw new ActionError(
              "A published article can't have a future date. Unpublish it to schedule instead.",
              400,
              { publishedAt: "Published articles can't be dated in the future." },
            );
          }
          const contentChanged =
            existing.title !== values.title ||
            existing.excerpt !== values.excerpt ||
            existing.content !== values.content;
          data = {
            ...data,
            publishedAt: chosenDate ?? existing.publishedAt ?? now,
            ...(contentChanged && { contentUpdatedAt: now }),
          };
          revisionReason = "updated";
        }
        data = {
          ...data,
          autosave: Prisma.DbNull,
          autosavedAt: null,
        };
        affectsSite = true;
        break;
      }
      case "unpublish": {
        if (!existing || !isLive) {
          throw new ActionError("This article is already a draft.");
        }
        const neverWentLive = !existing.publishedAt || existing.publishedAt > now;
        data = {
          ...data,
          status: "DRAFT",
          scheduledAt: null,
          publishedAt: neverWentLive ? null : existing.publishedAt,
          autosave: Prisma.DbNull,
          autosavedAt: null,
        };
        if (status === "PUBLISHED") revisionReason = "unpublished";
        affectsSite = true;
        break;
      }
    }

    // ---- Write --------------------------------------------------------------
    const blog = await db.$transaction(async (tx) => {
      let id: string;

      if (existing) {
        const { count } = await tx.blog.updateMany({
          where: { id: existing.id, version: existing.version },
          data: { ...data, version: { increment: 1 }, updatedById: admin.id },
        });
        if (count === 0) throw conflictError();
        id = existing.id;

        // First edit of a live article that predates revision history: keep the original too.
        if (revisionReason === "updated" && existing._count.revisions === 0) {
          await createRevision(tx, id, toFormValues(existing), "published", existing.updatedById);
        }
        if (existing.status === "PUBLISHED" && existing.slug !== values.slug) {
          await recordSlugChange(tx, id, existing.slug, values.slug);
        }
      } else {
        const created = await tx.blog.create({
          data: {
            ...(data as Prisma.BlogUncheckedCreateInput),
            createdById: admin.id,
            updatedById: admin.id,
          },
          select: { id: true },
        });
        id = created.id;
      }

      await writeRelations(tx, id, values);
      if (intent !== "autosave" && intent !== "draft") {
        await releaseSlugPath(tx, values.slug);
      }
      if (revisionReason) {
        await createRevision(tx, id, values, revisionReason, admin.id);
      }

      return tx.blog.findUniqueOrThrow({ where: { id }, include: blogEditorInclude });
    });

    revalidateAdmin(blog.id);
    if (affectsSite) revalidateSite([existing?.slug, blog.slug]);

    const messages: Record<typeof intent, string> = {
      autosave: "Draft saved",
      draft: "Draft saved",
      publish: "Article published",
      schedule: "Article scheduled",
      update: blog.status === "SCHEDULED" ? "Scheduled article updated" : "Article updated",
      unpublish: "Article unpublished and moved to drafts",
    };

    return {
      ok: true,
      message: messages[intent],
      data: { blog: toEditorMeta(blog), values: toFormValues(blog) },
    };
  });
}

/** Throws away autosaved edits to a live article. */
const importMarkdownSchema = z.object({
  markdown: z
    .string()
    .max(MARKDOWN_MAX_CHARS, "This file is too large to import. Split it or remove embedded images.")
    .refine((value) => value.trim().length > 0, "This file is empty."),
  blogId: idSchema.nullable(),
});

/**
 * Reads a blog Markdown file into editor values. Writes nothing: the editor
 * shows the result, and it is saved through `saveBlog` like any other edit.
 */
export async function importMarkdown(input: {
  markdown: string;
  blogId: string | null;
}): Promise<ActionResult<MarkdownImportResult>> {
  return runAction(async () => {
    await requireActionAdmin();
    const { markdown, blogId } = importMarkdownSchema.parse(input);
    const result = await parseBlogMarkdown(markdown, { blogId });
    return { ok: true, data: result };
  });
}

export async function discardAutosave(id: string): Promise<ActionResult<SaveBlogResult>> {
  return runAction(async () => {
    await requireActionAdmin();
    const blogId = idSchema.parse(id);

    const blog = await db.blog.update({
      where: { id: blogId },
      data: { autosave: Prisma.DbNull, autosavedAt: null },
      include: blogEditorInclude,
    });
    revalidatePath(`/admin/blogs/${blog.id}`);
    return {
      ok: true,
      message: "Unsaved changes discarded",
      data: { blog: toEditorMeta(blog), values: toFormValues(blog) },
    };
  });
}

/** Publishes or unpublishes from the article list, without opening the editor. */
export async function setBlogPublished(
  id: string,
  publish: boolean,
): Promise<ActionResult> {
  return runAction(async () => {
    const admin = await requireActionAdmin();
    const blog = await db.blog.findUnique({
      where: { id: idSchema.parse(id) },
      include: blogEditorInclude,
    });
    if (!blog) throw new ActionError("This article no longer exists.", 404);

    const values = toFormValues(blog);
    const now = new Date();

    if (publish) {
      if (blog.status === "PUBLISHED") return { ok: true, message: "Already published" };
      const issues = publishIssues(values);
      if (Object.keys(issues).length) {
        throw new ActionError(`Can't publish yet: ${Object.values(issues)[0]}`);
      }
      const taken = await isSlugTaken(blog.slug, blog.id);
      if (taken) throw new ActionError(`The URL is already used by “${taken.title}”.`);

      await db.$transaction(async (tx) => {
        const { count } = await tx.blog.updateMany({
          where: { id: blog.id, version: blog.version },
          data: {
            status: "PUBLISHED",
            // A scheduled article published early goes live now.
            publishedAt:
              blog.publishedAt && blog.publishedAt <= now ? blog.publishedAt : now,
            scheduledAt: null,
            version: { increment: 1 },
            updatedById: admin.id,
          },
        });
        if (count === 0) throw conflictError();
        await releaseSlugPath(tx, blog.slug);
        await createRevision(tx, blog.id, values, "published", admin.id);
      });
    } else {
      if (blog.status === "DRAFT") return { ok: true, message: "Already a draft" };
      const neverWentLive = !blog.publishedAt || blog.publishedAt > now;
      await db.$transaction(async (tx) => {
        const { count } = await tx.blog.updateMany({
          where: { id: blog.id, version: blog.version },
          data: {
            status: "DRAFT",
            scheduledAt: null,
            publishedAt: neverWentLive ? null : blog.publishedAt,
            version: { increment: 1 },
            updatedById: admin.id,
          },
        });
        if (count === 0) throw conflictError();
        if (blog.status === "PUBLISHED") {
          await createRevision(tx, blog.id, values, "unpublished", admin.id);
        }
      });
    }

    revalidateAdmin(blog.id);
    revalidateSite([blog.slug]);
    return {
      ok: true,
      message: publish ? `Published “${blog.title}”` : `Unpublished “${blog.title}”`,
    };
  });
}

export async function duplicateBlog(id: string): Promise<ActionResult<{ id: string }>> {
  return runAction(async () => {
    const admin = await requireActionAdmin();
    const source = await db.blog.findUnique({
      where: { id: idSchema.parse(id) },
      include: blogEditorInclude,
    });
    if (!source) throw new ActionError("This article no longer exists.", 404);

    const values = toFormValues(source);
    const slug = await uniqueSlug(`${source.slug}-copy`, async (candidate) =>
      Boolean(await isSlugTaken(candidate, null)),
    );
    const copy: BlogFormValues = {
      ...values,
      title: `${values.title} (Copy)`.slice(0, 200),
      slug,
      publishedAt: null,
    };

    const created = await db.$transaction(async (tx) => {
      const blog = await tx.blog.create({
        data: {
          ...blogColumns(copy),
          status: "DRAFT",
          createdById: admin.id,
          updatedById: admin.id,
        },
        select: { id: true },
      });
      await writeRelations(tx, blog.id, copy);
      return blog;
    });

    revalidateAdmin();
    return { ok: true, message: "Copy created as a draft", data: { id: created.id } };
  });
}

export async function deleteBlog(id: string): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const blog = await db.blog.findUnique({
      where: { id: idSchema.parse(id) },
      select: { id: true, slug: true, title: true, status: true },
    });
    if (!blog) throw new ActionError("This article was already deleted.", 404);

    await db.blog.delete({ where: { id: blog.id } });

    revalidateAdmin();
    if (blog.status !== "DRAFT") revalidateSite([blog.slug]);
    return { ok: true, message: `Deleted “${blog.title}”` };
  });
}

/**
 * Restores a revision. Live articles go live with the restored content right
 * away; the state being replaced is kept as a revision first.
 */
export async function restoreRevision(revisionId: string): Promise<ActionResult> {
  return runAction(async () => {
    const admin = await requireActionAdmin();
    const revision = await db.blogRevision.findUnique({
      where: { id: idSchema.parse(revisionId) },
      include: { blog: { include: blogEditorInclude } },
    });
    if (!revision) throw new ActionError("That revision no longer exists.", 404);

    const { blog } = revision;
    const current = toFormValues(blog);
    const snapshot = parseSnapshot(revision.snapshot, current);
    if (!snapshot) throw new ActionError("This revision can't be restored: its data is incomplete.");

    // A restore brings back content, not the URL or publishing dates: changing a
    // live article's address is a separate, deliberate edit.
    const values = {
      ...(await resolveReferences(normalizeValues(snapshot), blog.id)),
      slug: blog.slug,
      publishedAt: current.publishedAt,
    };

    await db.$transaction(async (tx) => {
      await createRevision(tx, blog.id, current, "updated", blog.updatedById);
      const { count } = await tx.blog.updateMany({
        where: { id: blog.id, version: blog.version },
        data: {
          ...blogColumns(values),
          autosave: Prisma.DbNull,
          autosavedAt: null,
          version: { increment: 1 },
          updatedById: admin.id,
          ...(blog.status === "PUBLISHED" && { contentUpdatedAt: new Date() }),
        },
      });
      if (count === 0) throw conflictError();
      await writeRelations(tx, blog.id, values);
      await createRevision(tx, blog.id, values, "restored", admin.id);
    });

    revalidateAdmin(blog.id);
    revalidatePath(`/admin/blogs/${blog.id}/revisions`);
    if (blog.status !== "DRAFT") revalidateSite([blog.slug]);
    return {
      ok: true,
      message:
        blog.status === "PUBLISHED"
          ? "Revision restored and published"
          : "Revision restored",
    };
  });
}

/** Live slug availability for the editor's slug field. */
export async function checkSlugAvailability(
  slug: string,
  exceptId: string | null,
): Promise<ActionResult<{ available: boolean; usedBy: string | null }>> {
  return runAction(async () => {
    await requireActionAdmin();
    const value = z.string().max(200).parse(slug);
    const taken = await isSlugTaken(value, exceptId ? idSchema.parse(exceptId) : null);
    return { ok: true, data: { available: !taken, usedBy: taken?.title ?? null } };
  });
}

export type BlogSearchResult = {
  id: string;
  title: string;
  slug: string;
  status: "DRAFT" | "SCHEDULED" | "PUBLISHED";
  featuredImage: string | null;
  category: string | null;
};

/** Article search for internal links and related-article pickers. */
export async function searchBlogs(
  query: string,
  { excludeId, publishedOnly = false }: { excludeId?: string | null; publishedOnly?: boolean } = {},
): Promise<ActionResult<BlogSearchResult[]>> {
  return runAction(async () => {
    await requireActionAdmin();
    const q = z.string().max(200).parse(query).trim();

    const rows = await db.blog.findMany({
      where: {
        ...(excludeId && { NOT: { id: excludeId } }),
        ...(publishedOnly && { status: { not: "DRAFT" } }),
        ...(q && {
          OR: [
            { title: { contains: q, mode: "insensitive" } },
            { slug: { contains: q, mode: "insensitive" } },
          ],
        }),
      },
      select: {
        id: true,
        title: true,
        slug: true,
        status: true,
        featuredImage: true,
        category: { select: { name: true } },
      },
      orderBy: [{ status: "desc" }, { updatedAt: "desc" }],
      take: 12,
    });

    return {
      ok: true,
      data: rows.map((row) => ({
        id: row.id,
        title: row.title || "Untitled",
        slug: row.slug,
        status: row.status,
        featuredImage: row.featuredImage,
        category: row.category?.name ?? null,
      })),
    };
  });
}

/** Summaries for a set of IDs, in the given order (for the related-articles list). */
export async function getBlogSummaries(ids: string[]): Promise<ActionResult<BlogSearchResult[]>> {
  return runAction(async () => {
    await requireActionAdmin();
    const list = z.array(idSchema).max(50).parse(ids);
    if (!list.length) return { ok: true, data: [] };

    const rows = await db.blog.findMany({
      where: { id: { in: list } },
      select: {
        id: true,
        title: true,
        slug: true,
        status: true,
        featuredImage: true,
        category: { select: { name: true } },
      },
    });
    const byId = new Map(rows.map((row) => [row.id, row]));
    return {
      ok: true,
      data: list.flatMap((blogId) => {
        const row = byId.get(blogId);
        return row
          ? [
              {
                id: row.id,
                title: row.title || "Untitled",
                slug: row.slug,
                status: row.status,
                featuredImage: row.featuredImage,
                category: row.category?.name ?? null,
              },
            ]
          : [];
      }),
    };
  });
}

/** What automatic mode would pick right now, for the editor's Related tab. */
export async function previewAutomaticRelated(input: {
  blogId: string | null;
  categoryId: string | null;
  tags: string[];
}): Promise<ActionResult<BlogSearchResult[]>> {
  return runAction(async () => {
    await requireActionAdmin();
    const { blogId, categoryId, tags } = z
      .object({
        blogId: idSchema.nullable(),
        categoryId: idSchema.nullable(),
        tags: z.array(z.string().max(40)).max(20),
      })
      .parse(input);

    const rows = await automaticRelated({
      excludeId: blogId,
      categoryId,
      tagSlugs: tags.map((tag) => slugify(tag, 60)).filter(Boolean),
    });
    return {
      ok: true,
      data: rows.map((row) => ({
        id: row.id,
        title: row.title,
        slug: row.slug,
        status: "PUBLISHED" as const,
        featuredImage: row.featuredImage,
        category: row.category?.name ?? null,
      })),
    };
  });
}
