"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 { cmsMessage, cmsPaths, cmsRequest } from "@/lib/cms/api";

import { redirectFormSchema, type RedirectFormInput } from "./schemas";

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

/**
 * `POST admin/redirects`. Laravel rejects duplicates, loops and paths an
 * article lives at, collapses chains and refreshes the website.
 */
export async function createRedirect(
  input: RedirectFormInput,
): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const { fromPath, toPath, permanent } = redirectFormSchema.parse(input);

    const destinationPath = toPath.startsWith("/")
      ? toPath.replace(/[?#].*$/, "")
      : toPath.toLowerCase();
    if (destinationPath === fromPath) {
      throw new ActionError("A redirect can't point to itself.", 400, {
        toPath: "Choose a different destination.",
      });
    }

    const body = await cmsRequest(cmsPaths.redirects, {
      json: { fromPath, toPath, permanent },
    });

    revalidatePath("/admin/seo");
    refreshWebsite();
    return { ok: true, message: cmsMessage(body, "Redirect added.") };
  });
}

/** `DELETE admin/redirects/{id}`. */
export async function deleteRedirect(id: string): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const body = await cmsRequest(cmsPaths.redirect(idSchema.parse(id)), {
      method: "DELETE",
    });

    revalidatePath("/admin/seo");
    refreshWebsite();
    return { ok: true, message: cmsMessage(body, "Redirect deleted.") };
  });
}
