import "server-only";

import {
  bool,
  cmsData,
  cmsPaths,
  idOf,
  isoOrNull,
  num,
  paginated,
  relation,
  str,
} from "@/lib/cms/api";

/** A redirect row as sent to Client Components. */
export type RedirectRow = {
  id: string;
  fromPath: string;
  toPath: string;
  permanent: boolean;
  hits: number;
  lastHitAt: string | null;
  createdAt: string;
  /** The article whose slug change created it, if any. */
  blog: { id: string; title: string } | null;
};

/** A `blog_redirects` row from the Laravel CMS. */
function toRedirectRow(row: unknown): RedirectRow {
  const blog = relation(row, "blog");
  return {
    id: idOf(row),
    fromPath: str(row, "from_path"),
    toPath: str(row, "to_path"),
    permanent: bool(row, "permanent", true),
    hits: num(row, "hits"),
    lastHitAt: isoOrNull(row, "last_hit_at"),
    createdAt: isoOrNull(row, "created_at") ?? new Date(0).toISOString(),
    blog: blog
      ? { id: idOf(blog), title: str(blog, "title") || "Untitled" }
      : null,
  };
}

/** `GET admin/redirects?q=&page=&pageSize=`, newest first. */
export async function listRedirects({
  query,
  page = 1,
  pageSize = 20,
}: {
  query?: string;
  page?: number;
  pageSize?: number;
}) {
  const data = await cmsData<unknown>(cmsPaths.redirects, {
    query: { q: query?.trim() || undefined, page, pageSize },
  });
  const { items, total } = paginated(data, toRedirectRow);
  return { items, total, page, pageSize };
}

/** Redirects in total. */
export async function countRedirects() {
  return (await listRedirects({ page: 1, pageSize: 1 })).total;
}
