/** سرویس مجله: مقاله‌های منتشرشده برای صفحات عمومی، sitemap و llms.txt */
import "server-only";
import { cache } from "react";
import { db } from "@/lib/db";

export const MAG_PAGE_SIZE = 9;

export type FaqItem = { q: string; a: string };
export const asFaq = (v: unknown): FaqItem[] =>
  Array.isArray(v) ? v.filter((x): x is FaqItem => !!x && typeof x.q === "string" && typeof x.a === "string") : [];

const published = () => ({ status: "PUBLISHED" as const, publishedAt: { lte: new Date() } });

export async function listArticles(page = 1) {
  const where = published();
  const [rows, total] = await Promise.all([
    db.article.findMany({
      where,
      orderBy: { publishedAt: "desc" },
      skip: (page - 1) * MAG_PAGE_SIZE,
      take: MAG_PAGE_SIZE,
      select: { slug: true, title: true, excerpt: true, coverUrl: true, coverAlt: true, publishedAt: true, body: true },
    }),
    db.article.count({ where }),
  ]);
  return { rows, total, pageCount: Math.max(1, Math.ceil(total / MAG_PAGE_SIZE)) };
}

/** مقاله با اسلاگ؛ پیش‌نویس فقط با preview=true (برای مدیر) برگردانده می‌شود */
export const getArticle = cache(async (slug: string, preview = false) => {
  const a = await db.article.findUnique({ where: { slug } });
  if (!a) return undefined;
  if (!preview && (a.status !== "PUBLISHED" || !a.publishedAt || a.publishedAt > new Date())) return undefined;
  return { ...a, faq: asFaq(a.faq) };
});

/** آدرس فعلی مقاله‌ای که این اسلاگ قبلاً آدرسش بوده (برای ریدایرکت ۳۰۱) */
export async function findMovedArticle(slug: string) {
  const a = await db.article.findFirst({ where: { oldSlugs: { has: slug }, ...published() }, select: { slug: true } });
  return a?.slug;
}

export async function getRelatedArticles(slug: string, limit = 3) {
  return db.article.findMany({
    where: { ...published(), slug: { not: slug } },
    orderBy: { publishedAt: "desc" },
    take: limit,
    select: { slug: true, title: true, excerpt: true, coverUrl: true, coverAlt: true, publishedAt: true },
  });
}

export async function getAllArticleRefs() {
  return db.article.findMany({ where: published(), select: { slug: true, title: true, excerpt: true, updatedAt: true }, orderBy: { publishedAt: "desc" } });
}
