"use server";

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

import { ActionError, runAction, type ActionResult } from "@/lib/actions";
import { refreshWebsite } from "@/lib/site";
import { requireActionAdmin } from "@/lib/auth/guards";
import { CmsError, cmsMessage, cmsPaths, cmsRequest } from "@/lib/cms/api";
import { cleanText } from "@/lib/utils";

import { authorInputSchema, type AuthorInput } from "./schemas";

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

/** Validates dialog input and cleans it into the request body. */
function toAuthorData(input: AuthorInput) {
  const values = authorInputSchema.parse(input);
  const name = cleanText(values.name);
  if (!name) {
    throw new ActionError("Enter the author's name.", 400, {
      name: "Enter the author's name.",
    });
  }
  return {
    name,
    slug: values.slug,
    role: values.role && (cleanText(values.role) || null),
    bio: values.bio && (cleanText(values.bio) || null),
    profileImage: values.profileImage,
    status: values.status,
  };
}

/** A 404 for a known route means the author is gone: refresh the stale list. */
function rethrowNotFound(error: unknown): never {
  if (
    error instanceof CmsError &&
    error.status === 404 &&
    !error.missingRoute
  ) {
    revalidatePath("/admin/authors");
    throw new ActionError(
      "This author no longer exists. They may have been deleted.",
      404,
    );
  }
  throw error;
}

/** `POST admin/authors`. Laravel checks the slug and refreshes the website. */
export async function createAuthor(input: AuthorInput): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const data = toAuthorData(input);
    const body = await cmsRequest(cmsPaths.authors, {
      method: "POST",
      json: data,
    });

    revalidatePath("/admin/authors");
    refreshWebsite();
    return {
      ok: true,
      message: cmsMessage(body, `Author “${data.name}” added.`),
    };
  });
}

/** `PUT admin/authors/{id}` */
export async function updateAuthor(
  id: string,
  input: AuthorInput,
): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const authorId = idSchema.parse(id);
    const data = toAuthorData(input);
    const body = await cmsRequest(cmsPaths.author(authorId), {
      method: "PUT",
      json: data,
    }).catch(rethrowNotFound);

    revalidatePath("/admin/authors");
    refreshWebsite();
    return {
      ok: true,
      message: cmsMessage(body, `Author “${data.name}” updated.`),
    };
  });
}

/** `DELETE admin/authors/{id}`. Their articles stay as they are, without a byline. */
export async function deleteAuthor(id: string): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const authorId = idSchema.parse(id);
    const body = await cmsRequest(cmsPaths.author(authorId), {
      method: "DELETE",
    }).catch(rethrowNotFound);

    revalidatePath("/admin/authors");
    refreshWebsite();
    return {
      ok: true,
      message: cmsMessage(
        body,
        "Author deleted. Their articles no longer have a byline.",
      ),
    };
  });
}
