/**
 * بازسازی متن جستجوی محصولات.
 * نام برند و دسته داخل searchText هر محصول ذخیره شده است؛ بعد از تغییر نام آن‌ها در پنل،
 * متن جستجوی محصولات وابسته باید دوباره ساخته شود تا جستجو با نام جدید کار کند.
 */
import "server-only";
import { db } from "@/lib/db";
import { buildSearchText } from "@/lib/search-text";
import type { Prisma } from "@/generated/prisma/client";

export async function rebuildSearchText(where: Prisma.ProductWhereInput) {
  const rows = await db.product.findMany({
    where,
    select: {
      id: true,
      name: true,
      summary: true,
      brand: { select: { name: true, nameEn: true } },
      category: { select: { name: true, parent: { select: { name: true } } } },
    },
  });
  // هر محصول یک به‌روزرسانی کوچک است؛ در یک تراکنش انجام می‌شود
  await db.$transaction(
    rows.map((p) =>
      db.product.update({
        where: { id: p.id },
        data: { searchText: buildSearchText({ name: p.name, summary: p.summary, brand: p.brand, categories: [p.category.name, p.category.parent?.name ?? ""] }) },
      }),
    ),
  );
  return rows.length;
}
