/** داده‌های لازم فرم محصول (برندها، دسته‌ها، انواع پوست) */
import "server-only";
import { db } from "@/lib/db";
import type { ProductFormInput } from "./products";
import { effectiveRate, getCurrencySettings, originalCategoryIds } from "@/server/services/currency";

export async function productFormOptions() {
  const [brands, cats, skinTypes, originalIds, fx] = await Promise.all([
    db.brand.findMany({ orderBy: { name: "asc" }, select: { id: true, name: true } }),
    db.category.findMany({ orderBy: { sortOrder: "asc" }, include: { parent: { select: { name: true } } } }),
    db.skinType.findMany({ orderBy: { id: "asc" } }),
    originalCategoryIds(),
    getCurrencySettings(),
  ]);
  const categories = cats.map((c) => ({ id: c.id, name: c.parent ? `${c.parent.name} › ${c.name}` : c.name })).sort((a, b) => a.name.localeCompare(b.name, "fa"));
  // برای پیش‌نمایش قیمت تومانی در فرم (همان فرمول سرور)؛ نرخ فقط به پنل مدیر فرستاده می‌شود
  const currency = { originalCategoryIds: originalIds, rate: effectiveRate(fx), roundTo: fx.roundTo, roundMode: fx.roundMode };
  return { brands, categories, skinTypes, currency };
}

export async function productFormInitial(id: number): Promise<ProductFormInput | null> {
  const p = await db.product.findUnique({ where: { id }, include: { skinTypes: { select: { id: true } }, variants: { orderBy: { sortOrder: "asc" } } } });
  if (!p) return null;
  return {
    name: p.name,
    slug: p.slug,
    brandId: p.brandId,
    categoryId: p.categoryId,
    skinTypeIds: p.skinTypes.map((s) => s.id),
    summary: p.summary,
    description: p.description,
    howToUse: p.howToUse,
    ingredients: p.ingredients,
    ircCode: p.ircCode,
    madeIn: p.madeIn,
    shape: p.shape as ProductFormInput["shape"],
    tone: p.tone,
    tags: p.tags,
    isActive: p.isActive,
    variants: p.variants.map((v) => ({
      id: v.id,
      sku: v.sku,
      colorName: v.colorName ?? "",
      colorHex: v.colorHex ?? "",
      size: v.size ?? "",
      price: v.price,
      compareAtPrice: v.compareAtPrice ?? "",
      priceUsd: v.priceUsdCents != null ? v.priceUsdCents / 100 : undefined,
      compareAtUsd: v.compareAtUsdCents != null ? v.compareAtUsdCents / 100 : undefined,
      stock: v.stock,
      isActive: v.isActive,
    })),
  };
}

export const blankProduct: ProductFormInput = {
  name: "", slug: "", brandId: "", categoryId: "", skinTypeIds: [], summary: "", description: "", howToUse: "", ingredients: "",
  ircCode: "", madeIn: "", shape: "bottle", tone: "#e8e2d8", tags: ["new"], isActive: true,
  variants: [{ sku: "", colorName: "", colorHex: "", size: "", price: 0, compareAtPrice: "", stock: 0, isActive: true }],
};
