"use server";
import { prisma } from "@/lib/prisma";
import { format } from "date-fns-jalali";

export async function getProductAnalytics(productId: string) {
  try {
    // 1. Fetch Sales (from non-cancelled Orders containing this product)
    const orderItems = await prisma.orderItem.findMany({
      where: {
        productId,
        order: { status: { notIn: ["CANCELLED", "REFUNDED", "FAILED"] } }
      },
      include: { order: true }
    });

    let totalSold = 0;
    let totalRevenue = 0;
    
    // Group sales history by month or week if needed, for simplicity we just sum it up
    orderItems.forEach(item => {
      totalSold += item.quantity;
      totalRevenue += (item.price * item.quantity);
    });

    // 2. Fetch Purchases (from Purchase model containing this product)
    const purchaseItems = await prisma.purchaseItem.findMany({
      where: { productId },
      include: {
        purchase: {
          include: { supplier: true }
        }
      },
      orderBy: { purchase: { purchaseDate: "asc" } }
    });

    let firstPurchasePrice = 0;
    let lastPurchasePrice = 0;
    const purchaseHistory: any[] = [];
    const suppliersMap = new Map<string, { name: string; count: number; totalAmt: number; lastDate: Date }>();

    purchaseItems.forEach((pi, index) => {
      if (index === 0) firstPurchasePrice = pi.purchasePrice;
      if (index === purchaseItems.length - 1) lastPurchasePrice = pi.purchasePrice;

      purchaseHistory.push({
        date: format(new Date(pi.purchase.purchaseDate), "yyyy/MM/dd"),
        قیمت: pi.purchasePrice
      });

      const supId = pi.purchase.supplierId || "unknown";
      if (!suppliersMap.has(supId)) {
        suppliersMap.set(supId, { 
          name: pi.purchase.supplier?.name || "تامین‌کننده نامشخص", 
          count: 0, 
          totalAmt: 0, 
          lastDate: pi.purchase.purchaseDate 
        });
      }
      const s = suppliersMap.get(supId)!;
      s.count += pi.quantity;
      s.totalAmt += (pi.purchasePrice * pi.quantity);
      if (new Date(pi.purchase.purchaseDate) > new Date(s.lastDate)) {
        s.lastDate = pi.purchase.purchaseDate;
      }
    });

    const suppliers = Array.from(suppliersMap.values()).map(s => ({
      name: s.name,
      avgPrice: s.count > 0 ? Math.round(s.totalAmt / s.count) : 0,
      lastDate: format(new Date(s.lastDate), "yyyy/MM/dd")
    }));

    return { 
      success: true, 
      data: {
        stats: {
          totalSold,
          totalRevenue,
          firstPurchasePrice,
          lastPurchasePrice,
          suppliers
        },
        purchaseHistory
      }
    };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}
