/** داده‌های مشترک صفحه‌های ایجاد/ویرایش مقاله */
import "server-only";
import { db } from "@/lib/db";
import { site } from "@/lib/site";
import { aiReady } from "@/server/services/ai";
import { asFaq } from "@/server/services/magazine";
import type { ArticleFormValue } from "@/components/admin/ArticleForm";

export async function articleFormOptions() {
  const [products, aiEnabled] = await Promise.all([
    db.product.findMany({ orderBy: { id: "asc" }, select: { id: true, name: true, brand: { select: { name: true } } } }),
    aiReady(),
  ]);
  return { products: products.map((p) => ({ id: p.id, name: p.name, brand: p.brand.name })), aiEnabled, siteUrl: site.url };
}

export const blankArticle: ArticleFormValue = {
  title: "",
  slug: "",
  excerpt: "",
  body: "## \n\n",
  coverUrl: "",
  coverAlt: "",
  seoTitle: "",
  seoDescription: "",
  focusKeyword: "",
  faq: [],
  ctaLabel: "",
  ctaHref: "",
  productIds: [],
  authorName: "",
};

export async function articleFormInitial(id: string) {
  const a = await db.article.findUnique({ where: { id } });
  if (!a) return null;
  const value: ArticleFormValue = {
    title: a.title,
    slug: a.slug,
    excerpt: a.excerpt,
    body: a.body,
    coverUrl: a.coverUrl ?? "",
    coverAlt: a.coverAlt ?? "",
    seoTitle: a.seoTitle ?? "",
    seoDescription: a.seoDescription ?? "",
    focusKeyword: a.focusKeyword ?? "",
    faq: asFaq(a.faq),
    ctaLabel: a.ctaLabel ?? "",
    ctaHref: a.ctaHref ?? "",
    productIds: a.productIds,
    authorName: a.authorName ?? "",
  };
  return { value, published: a.status === "PUBLISHED", slug: a.slug };
}
