"use server";

/**
 * بهینه‌سازی خودکار سئو/GEO: فقط موارد خالی یا خارج از اندازه اصلاح می‌شوند و متنی که مدیر نوشته دست نمی‌خورد.
 * - متن جایگزین عکس‌های محصول (نام محصول + برند + رنگ)
 * - توضیح دسته‌های بدون توضیح (برای توضیحات متای صفحه دسته)
 * - متن جایگزین عکس بنرها
 * - فیلدهای سئوی مقاله‌ها (تگ عنوان، توضیحات متا، کلمه کلیدی، alt کاور و عکس‌های متن)
 */
import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";
import { autoOptimizeArticle } from "@/lib/seo-check";
import { asFaq } from "@/server/services/magazine";
import { refreshStorefront } from "./cache";
import { requireStaff } from "./guard";

export async function autoFixSeoAction(): Promise<{ fixed: number }> {
  await requireStaff("seo");
  let fixed = 0;

  const images = await db.productImage.findMany({ include: { product: { select: { name: true, brand: { select: { name: true } }, variants: { select: { id: true, colorName: true } } } } } });
  for (const img of images.filter((i) => i.alt.trim().length < 3)) {
    const color = img.variantId ? img.product.variants.find((v) => v.id === img.variantId)?.colorName : undefined;
    await db.productImage.update({ where: { id: img.id }, data: { alt: [img.product.name, img.product.brand.name, color && `رنگ ${color}`].filter(Boolean).join(" ") } });
    fixed++;
  }

  const cats = await db.category.findMany({ include: { parent: { select: { name: true } } } });
  for (const c of cats.filter((c) => !c.description || c.description.length < 50)) {
    const description = `خرید آنلاین ${c.name}${c.parent ? ` (${c.parent.name})` : ""} اصل از برندهای معتبر با ضمانت اصالت کالا، مقایسه قیمت و نظر خریداران، و ارسال سریع به سراسر ایران از زهورا.`;
    await db.category.update({ where: { id: c.id }, data: { description } });
    fixed++;
  }

  const banners = await db.banner.findMany({ where: { imageUrl: { not: null } } });
  for (const b of banners.filter((b) => !b.imageAlt?.trim())) {
    await db.banner.update({ where: { id: b.id }, data: { imageAlt: `${b.title} — ${b.subtitle}`.slice(0, 140) } });
    fixed++;
  }

  const articles = await db.article.findMany();
  for (const a of articles) {
    const input = { ...a, faq: asFaq(a.faq) };
    const o = autoOptimizeArticle(input);
    const changed = (["slug", "excerpt", "seoTitle", "seoDescription", "focusKeyword", "coverAlt", "body"] as const).filter((k) => o[k] !== input[k]);
    if (!changed.length) continue;
    // اسلاگ مقاله منتشرشده عوض نمی‌شود تا لینک‌های قبلی خراب نشوند
    const slug = a.status === "PUBLISHED" ? a.slug : o.slug;
    const clash = slug !== a.slug && (await db.article.findFirst({ where: { slug, id: { not: a.id } } }));
    await db.article.update({
      where: { id: a.id },
      data: { slug: clash ? a.slug : slug, excerpt: o.excerpt, seoTitle: o.seoTitle, seoDescription: o.seoDescription, focusKeyword: o.focusKeyword, coverAlt: o.coverAlt, body: o.body },
    });
    fixed++;
  }

  refreshStorefront({ categories: true });
  revalidatePath("/admin/seo");
  return { fixed };
}
