"use server";

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

import { runAction, type ActionResult } from "@/lib/actions";
import { requireActionAdmin } from "@/lib/auth/guards";
import {
  cmsMessage,
  cmsPaths,
  cmsRequest,
  field,
  str,
  strOrNull,
} from "@/lib/cms/api";
import { cleanText } from "@/lib/utils";

import { findMediaUsage, type MediaUsage } from "./queries";

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

const mediaDetailsSchema = z.object({
  altText: z.string().max(300, "Keep alt text under 300 characters."),
  title: z.string().max(200, "Keep the title under 200 characters."),
});

/** `PATCH admin/media/{id}`. */
export async function updateMedia(
  id: string,
  input: { altText: string; title: string },
): Promise<ActionResult<{ altText: string; title: string | null }>> {
  return runAction(async () => {
    await requireActionAdmin();
    const values = mediaDetailsSchema.parse(input);
    const altText = cleanText(values.altText);
    const title = cleanText(values.title) || null;

    const body = await cmsRequest(cmsPaths.mediaItem(idSchema.parse(id)), {
      method: "PATCH",
      json: { altText, title },
    });
    const data = field(body, "data") ?? body;
    const row = field(data, "media") ?? data;
    const saved =
      row && typeof row === "object" && field(row, "alt_text") !== undefined
        ? { altText: str(row, "alt_text"), title: strOrNull(row, "title") }
        : { altText, title };

    revalidatePath("/admin/media");
    return {
      ok: true,
      message: cmsMessage(body, "Image details saved."),
      data: saved,
    };
  });
}

/** Where an image is used, so the delete confirmation can warn about broken images. */
export async function getMediaUsage(
  id: string,
): Promise<ActionResult<MediaUsage>> {
  return runAction(async () => {
    await requireActionAdmin();
    return { ok: true, data: await findMediaUsage(idSchema.parse(id)) };
  });
}

/** `DELETE admin/media/{id}`: Laravel deletes the file and the record. */
export async function deleteMedia(id: string): Promise<ActionResult> {
  return runAction(async () => {
    await requireActionAdmin();
    const body = await cmsRequest(cmsPaths.mediaItem(idSchema.parse(id)), {
      method: "DELETE",
    });
    revalidatePath("/admin/media");
    return { ok: true, message: cmsMessage(body, "Image deleted.") };
  });
}
