/** بررسی سراسری سئو و GEO سایت (محصولات، عکس‌ها، دسته‌ها، بنرها، مقاله‌ها) برای صفحه «سئو و GEO» پنل */
import "server-only";
import { db } from "@/lib/db";
import { faNumber } from "@/lib/format";
import { checkArticle } from "@/lib/seo-check";
import { asFaq } from "@/server/services/magazine";
import { getAiSettings } from "@/server/services/ai";

export interface AuditIssue {
  area: "محصول" | "عکس" | "دسته" | "بنر" | "مقاله" | "GEO";
  label: string;
  href?: string;
  /** با «بهینه‌سازی خودکار» درست می‌شود */
  auto: boolean;
}

export async function seoAudit() {
  const [products, images, categories, banners, articles, ai] = await Promise.all([
    db.product.findMany({ where: { isActive: true }, select: { id: true, name: true, summary: true, description: true, _count: { select: { images: true } } } }),
    db.productImage.findMany({ select: { id: true, alt: true, productId: true } }),
    db.category.findMany({ where: { isActive: true }, select: { id: true, name: true, description: true } }),
    db.banner.findMany({ where: { isActive: true }, select: { id: true, title: true, imageUrl: true, imageAlt: true } }),
    db.article.findMany(),
    getAiSettings(),
  ]);
  const issues: AuditIssue[] = [];

  const names = new Map<string, number>();
  for (const p of products) names.set(p.name, (names.get(p.name) ?? 0) + 1);
  for (const p of products) {
    const href = `/admin/products/${p.id}`;
    if (p._count.images === 0) issues.push({ area: "محصول", label: `«${p.name}» عکس واقعی ندارد`, href, auto: false });
    if (p.description.length < 150) issues.push({ area: "محصول", label: `توضیحات «${p.name}» کوتاه است (${faNumber(p.description.length)} کاراکتر)`, href, auto: false });
    if (p.summary.length < 40) issues.push({ area: "محصول", label: `خلاصه «${p.name}» برای توضیحات متا کوتاه است`, href, auto: false });
    if ((names.get(p.name) ?? 0) > 1) issues.push({ area: "محصول", label: `نام «${p.name}» تکراری است (عنوان صفحه تکراری)`, href, auto: false });
  }
  for (const img of images) if (img.alt.trim().length < 3) issues.push({ area: "عکس", label: "عکس محصول بدون متن جایگزین (alt)", href: `/admin/products/${img.productId}`, auto: true });
  for (const c of categories) if (!c.description || c.description.length < 50) issues.push({ area: "دسته", label: `دسته «${c.name}» توضیح ندارد`, href: "/admin/catalog", auto: true });
  for (const b of banners) if (b.imageUrl && !b.imageAlt?.trim()) issues.push({ area: "بنر", label: `عکس بنر «${b.title}» متن جایگزین ندارد`, href: "/admin/banners", auto: true });
  for (const a of articles) {
    const { checks } = checkArticle({ ...a, faq: asFaq(a.faq) });
    for (const c of checks.filter((c) => c.status !== "good")) issues.push({ area: "مقاله", label: `«${a.title}»: ${c.label}`, href: `/admin/magazine/${a.id}`, auto: !!c.autoFixable });
  }
  if (!ai.allowAiCrawlers) issues.push({ area: "GEO", label: "ربات‌های هوش مصنوعی مسدودند؛ سایت در پاسخ ChatGPT، Claude و Perplexity دیده نمی‌شود", href: "/admin/ai", auto: false });
  if (!articles.some((a) => a.status === "PUBLISHED")) issues.push({ area: "GEO", label: "هیچ مقاله منتشرشده‌ای نیست؛ محتوای راهنما مهم‌ترین منبع نقل‌شدن در موتورهای هوش مصنوعی است", href: "/admin/magazine/new", auto: false });

  // امتیاز = سهم بررسی‌های قبول‌شده از کل بررسی‌ها (هر محصول ۴ بررسی، هر مقاله حدود ۱۲)
  const total = products.length * 4 + images.length + categories.length + banners.length + articles.length * 12 + 2;
  const score = Math.max(0, Math.round((1 - issues.length / Math.max(total, 1)) * 100));
  return { issues, score, counts: { products: products.length, images: images.length, categories: categories.length, articles: articles.length } };
}
