"use server";

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

import { getCategoryOptions } from "@/features/categories/queries";
import { ActionError, runAction, type ActionResult } from "@/lib/actions";
import { refreshWebsite } from "@/lib/site";
import { requireActionAdmin } from "@/lib/auth/guards";
import {
  CmsError,
  cmsData,
  cmsMessage,
  cmsPaths,
  cmsRequest,
  field,
  idOf,
  isMissingRoute,
  list,
  paginated,
  relation,
  str,
  strOrNull,
} from "@/lib/cms/api";
import type { ContentStatus } from "@/lib/cms/types";

import {
  MARKDOWN_MAX_CHARS,
  parseBlogMarkdown,
  type MarkdownImportResult,
} from "./markdown-import";
import {
  blogFormSchema,
  saveIntents,
  type BlogFormValues,
  type SaveBlogResult,
} from "./schemas";
import { pendingFromRow, readBlogPayload, statusOf } from "./service";

/*
 * Every rule about saving (the status state machine, slug conflicts, slug
 * redirects, revisions, refreshing the website) runs on the Laravel CMS
 * (docs/laravel-blog-api.md §8.3). These actions validate the form, call the
 * API as the signed-in admin and map the answer for the editor.
 */

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

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

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

const saveMessages: Record<(typeof saveIntents)[number], string> = {
  autosave: "Draft saved",
  draft: "Draft saved",
  publish: "Article published",
  schedule: "Article scheduled",
  update: "Article updated",
  unpublish: "Article unpublished and moved to drafts",
};

/**
 * Saves the editor: `POST admin/blogs` for a new article, `PUT admin/blogs/{id}`
 * (with the version the editor loaded) for an existing one. `intent` decides
 * what happens to the article's status; see §8.3.
 */
export async function saveBlog(input: {
  id: string | null;
  version: number | null;
  intent: (typeof saveIntents)[number];
  values: BlogFormValues;
}): Promise<ActionResult<SaveBlogResult>> {
  return runAction(async () => {
    await requireActionAdmin();
    const { id, version, intent, values } = saveInputSchema.parse(input);

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

    const body = id
      ? await cmsRequest(cmsPaths.blog(id), {
          method: "PUT",
          json: { version, intent, values },
        })
      : await cmsRequest(cmsPaths.blogs, { json: { intent, values } });

    const saved = readBlogPayload(body.data ?? body);
    if (!saved.blog.id)
      throw new ActionError(
        "The CMS saved the article but didn't return it. Reload the page.",
      );

    // An autosave of a live article parks the edits; the row still holds the live version.
    if (intent === "autosave" && saved.blog.status !== "DRAFT") {
      saved.values = pendingFromRow(saved.row, values) ?? values;
    }

    revalidateAdmin(saved.blog.id);
    return {
      ok: true,
      message: cmsMessage(body, saveMessages[intent]),
      data: { blog: saved.blog, values: saved.values },
    };
  });
}

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 };
  });
}

/** Throws away autosaved edits to a live article (`DELETE admin/blogs/{id}/autosave`). */
export async function discardAutosave(
  id: string,
): Promise<ActionResult<SaveBlogResult>> {
  return runAction(async () => {
    await requireActionAdmin();
    const blogId = idSchema.parse(id);

    const body = await cmsRequest(cmsPaths.blogAction(blogId, "autosave"), {
      method: "DELETE",
    });
    // A 204 carries no article; read it back.
    const data =
      body.data ??
      (idOf(body) ? body : await cmsData<unknown>(cmsPaths.blog(blogId)));
    const { blog, values } = readBlogPayload(data);

    revalidatePath(`/admin/blogs/${blogId}`);
    return {
      ok: true,
      message: cmsMessage(body, "Unsaved changes discarded"),
      data: { blog: { ...blog, autosavedAt: null }, values },
    };
  });
}

/** Publishes or unpublishes from the article list (`POST admin/blogs/{id}/publish|unpublish`). */
export async function setBlogPublished(
  id: string,
  publish: boolean,
): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const blogId = idSchema.parse(id);
    const body = await cmsRequest(
      cmsPaths.blogAction(blogId, publish ? "publish" : "unpublish"),
      {
        method: "POST",
      },
    );
    const title = str(body.data, "title");
    revalidateAdmin(blogId);
    return {
      ok: true,
      message: cmsMessage(
        body,
        publish
          ? title
            ? `Published “${title}”`
            : "Article published"
          : title
            ? `Unpublished “${title}”`
            : "Article unpublished",
      ),
    };
  });
}

/**
 * Copies an article as a new draft (`POST admin/blogs/{id}/duplicate`). Until
 * the CMS has that endpoint, the copy is made by reading the article and
 * creating a draft from its values; Laravel picks a free slug for drafts.
 */
export async function duplicateBlog(
  id: string,
): Promise<ActionResult<{ id: string }>> {
  return runAction(async () => {
    await requireActionAdmin();
    const blogId = idSchema.parse(id);

    let body: Record<string, unknown>;
    try {
      body = await cmsRequest(cmsPaths.blogAction(blogId, "duplicate"), {
        method: "POST",
      });
    } catch (error) {
      if (!isMissingRoute(error)) throw error;
      const { values } = readBlogPayload(
        await cmsData<unknown>(cmsPaths.blog(blogId)),
      );
      const copy: BlogFormValues = {
        ...values,
        title: `${values.title} (Copy)`.slice(0, 200),
        slug: `${values.slug}-copy`.slice(0, 120),
        publishedAt: null,
      };
      body = await cmsRequest(cmsPaths.blogs, {
        json: { intent: "draft", values: copy },
      });
    }

    const created = readBlogPayload(body.data ?? body).blog;
    if (!created.id)
      throw new ActionError(
        "The CMS made the copy but didn't return it. Reload the list.",
      );
    revalidateAdmin();
    return {
      ok: true,
      message: "Copy created as a draft",
      data: { id: created.id },
    };
  });
}

/** `DELETE admin/blogs/{id}`. The CMS refreshes the website if the article was live. */
export async function deleteBlog(id: string): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const blogId = idSchema.parse(id);
    try {
      const body = await cmsRequest(cmsPaths.blog(blogId), {
        method: "DELETE",
      });
      revalidateAdmin();
      return { ok: true, message: cmsMessage(body, "Article deleted") };
    } catch (error) {
      if (
        error instanceof CmsError &&
        error.status === 404 &&
        !error.missingRoute
      ) {
        throw new ActionError("This article was already deleted.", 404);
      }
      throw error;
    }
  });
}

/**
 * Restores a revision (`POST admin/blogs/{id}/revisions/{revisionId}/restore`).
 * The CMS keeps the current slug and saves the replaced state as a revision first.
 */
export async function restoreRevision(
  blogId: string,
  revisionId: string,
): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const id = idSchema.parse(blogId);
    const body = await cmsRequest(
      `${cmsPaths.revision(id, idSchema.parse(revisionId))}/restore`,
      {
        method: "POST",
      },
    );
    revalidateAdmin(id);
    revalidatePath(`/admin/blogs/${id}/revisions`);
    return { ok: true, message: cmsMessage(body, "Revision restored") };
  });
}

export type BlogSearchResult = {
  id: string;
  title: string;
  slug: string;
  status: ContentStatus;
  featuredImage: string | null;
  category: string | null;
};

/** Article rows from the CMS list, searched by title, slug or excerpt. */
async function searchRows(q: string, pageSize: number) {
  const [body, categories] = await Promise.all([
    cmsData<unknown>(cmsPaths.blogs, {
      query: { q, pageSize, sort: "updated" },
    }),
    getCategoryOptions(),
  ]);
  const names = new Map(
    categories.map((category) => [category.id, category.name]),
  );
  return paginated(body, (row): BlogSearchResult => {
    const categoryId = strOrNull(row, "category_id");
    const category = relation(row, "category");
    return {
      id: idOf(row),
      title: str(row, "title") || "Untitled",
      slug: str(row, "slug"),
      status: statusOf(row),
      featuredImage: strOrNull(row, "featured_image"),
      category: category
        ? str(category, "name")
        : categoryId
          ? (names.get(categoryId) ?? null)
          : null,
    };
  }).items;
}

/**
 * Is a slug free? Uses `GET admin/blogs/slug-check` when the CMS has it,
 * otherwise searches the article list for an exact match.
 */
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).trim().toLowerCase();
    const excludeId = exceptId ? idSchema.parse(exceptId) : null;
    if (!value) return { ok: true, data: { available: true, usedBy: null } };

    try {
      const data = await cmsData<unknown>(cmsPaths.slugCheck, {
        query: { slug: value, excludeId },
      });
      const available = field(data, "available");
      if (typeof available === "boolean") {
        return {
          ok: true,
          data: { available, usedBy: strOrNull(data, "used_by") },
        };
      }
    } catch (error) {
      // Not built yet (or answered by `admin/blogs/{id}`): fall back to the list.
      if (
        !(error instanceof CmsError) ||
        (error.status !== 404 && error.status !== 405)
      )
        throw error;
    }

    const match = (await searchRows(value, 30)).find(
      (row) => row.slug === value && row.id !== excludeId,
    );
    return {
      ok: true,
      data: { available: !match, usedBy: match?.title ?? 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 searchRows(q, 30);
    return {
      ok: true,
      data: rows
        .filter(
          (row) =>
            row.id !== excludeId && (!publishedOnly || row.status !== "DRAFT"),
        )
        .slice(0, 12),
    };
  });
}

/** 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 listIds = z.array(idSchema).max(50).parse(ids);
    if (!listIds.length) return { ok: true, data: [] };

    const categories = await getCategoryOptions();
    const names = new Map(
      categories.map((category) => [category.id, category.name]),
    );
    const rows = await Promise.all(
      listIds.map(async (blogId) => {
        try {
          const { row, values, blog } = readBlogPayload(
            await cmsData<unknown>(cmsPaths.blog(blogId)),
          );
          const category = relation(row, "category");
          return {
            id: blog.id,
            title: values.title || "Untitled",
            slug: blog.slug,
            status: blog.status,
            featuredImage: values.featuredImage || null,
            category: category
              ? str(category, "name")
              : values.categoryId
                ? (names.get(values.categoryId) ?? null)
                : null,
          } satisfies BlogSearchResult;
        } catch (error) {
          // A picked article that was deleted since.
          if (
            error instanceof CmsError &&
            error.status === 404 &&
            !error.missingRoute
          )
            return null;
          throw error;
        }
      }),
    );
    return { ok: true, data: rows.filter((row) => row !== null) };
  });
}

/** What automatic mode would pick right now (`POST admin/blogs/related-preview`). */
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 body = await cmsData<unknown>(cmsPaths.relatedPreview, {
      json: { excludeId: blogId, categoryId, tags },
    });
    const rows = Array.isArray(body) ? body : list(body, "data");
    return {
      ok: true,
      data: rows.map((row) => {
        const category = relation(row, "category");
        return {
          id: idOf(row),
          title: str(row, "title"),
          slug: str(row, "slug"),
          status: "PUBLISHED" as const,
          featuredImage: strOrNull(row, "featured_image"),
          category: category
            ? str(category, "name")
            : strOrNull(row, "category"),
        };
      }),
    };
  });
}
