import "server-only";

import {
  cmsPaths,
  cmsRequest,
  field,
  idOf,
  isoOrNull,
  list,
  num,
  relation,
  str,
  strOrNull,
} from "@/lib/cms/api";
import { absoluteMediaUrl } from "@/lib/site";

import type { MediaItem, MediaListResponse } from "./types";

/** A `blog_media` row from the Laravel CMS (snake_case or camelCase). */
export function toMediaItem(row: unknown): MediaItem {
  const url = str(row, "url");
  const width = num(row, "width", NaN);
  const height = num(row, "height", NaN);
  // `uploaded_by` may be the relation or just the user's ID.
  const uploader = relation(row, "uploaded_by") ?? relation(row, "uploader");
  return {
    id: idOf(row),
    url,
    publicUrl: absoluteMediaUrl(url) ?? url,
    filename: str(row, "filename") || url.split("/").pop() || "image",
    mimeType: str(row, "mime_type"),
    size: num(row, "size"),
    width: Number.isFinite(width) ? width : null,
    height: Number.isFinite(height) ? height : null,
    altText: str(row, "alt_text"),
    title: strOrNull(row, "title"),
    createdAt: isoOrNull(row, "created_at") ?? new Date(0).toISOString(),
    uploadedBy: uploader
      ? strOrNull(uploader, "name")
      : strOrNull(row, "uploaded_by_name"),
  };
}

/** The media row inside a write response: `{media}`, `{data}`, `{data: {media}}` or the row itself. */
export function mediaFromBody(body: unknown): MediaItem | null {
  const data = field(body, "data") ?? body;
  const row = field(data, "media") ?? field(body, "media") ?? data;
  return row && typeof row === "object" && str(row, "url")
    ? toMediaItem(row)
    : null;
}

export type MediaPage = MediaListResponse & {
  /** Bytes stored in the whole library, when the CMS reports it. */
  totalBytes: number | null;
};

/** `GET admin/media?q=&page=&pageSize=`: Laravel paginator, newest first. */
export async function listMedia({
  query,
  page = 1,
  pageSize = 30,
}: {
  query?: string;
  page?: number;
  pageSize?: number;
}): Promise<MediaPage> {
  const size = Math.min(60, Math.max(1, pageSize));
  const body = await cmsRequest(cmsPaths.media, {
    query: { q: query?.trim() || undefined, page, pageSize: size },
  });
  // `{ok, data: paginator}`, the paginator itself, or a plain array.
  const paginator =
    field(body, "current_page") !== undefined
      ? body
      : (field(body, "data") ?? body);
  const rows = Array.isArray(paginator) ? paginator : list(paginator, "data");
  const totalBytes =
    field(body, "total_bytes") ?? field(paginator, "total_bytes");
  return {
    items: rows.map(toMediaItem),
    total: num(paginator, "total", rows.length),
    page,
    pageSize: size,
    totalBytes:
      totalBytes === undefined || totalBytes === null
        ? null
        : Number(totalBytes) || 0,
  };
}

export type MediaUsage = {
  blogs: { id: string; title: string }[];
  authors: { id: string; name: string }[];
};

/** `GET admin/media/{id}/usage`: articles and authors that use the image. */
export async function findMediaUsage(id: string): Promise<MediaUsage> {
  const body = await cmsRequest(cmsPaths.mediaUsage(id));
  const data = field(body, "data") ?? body;
  return {
    blogs: list(data, "blogs").map((row) => ({
      id: idOf(row),
      title: str(row, "title") || "Untitled",
    })),
    authors: list(data, "authors").map((row) => ({
      id: idOf(row),
      name: str(row, "name"),
    })),
  };
}
