"use server";
import { prisma } from "@/lib/prisma";
import { format } from "date-fns-jalali";

export async function getAccountingReports(timeframe: "DAILY" | "WEEKLY" | "MONTHLY" | "YEARLY") {
  try {
    // Determine start date based on timeframe
    const now = new Date();
    let startDate = new Date();
    
    if (timeframe === "DAILY") {
      startDate.setHours(0, 0, 0, 0);
    } else if (timeframe === "WEEKLY") {
      startDate.setDate(now.getDate() - 7);
      startDate.setHours(0, 0, 0, 0);
    } else if (timeframe === "MONTHLY") {
      startDate.setMonth(now.getMonth() - 1);
      startDate.setHours(0, 0, 0, 0);
    } else if (timeframe === "YEARLY") {
      startDate.setFullYear(now.getFullYear() - 1);
      startDate.setHours(0, 0, 0, 0);
    }

    // Fetch orders within the date range
    const orders = await prisma.order.findMany({
      where: {
        createdAt: { gte: startDate },
        status: { notIn: ["CANCELLED", "REFUNDED", "FAILED"] }
      },
      include: {
        items: true
      },
      orderBy: { createdAt: "asc" }
    });

    // Grouping and calculations
    let totalSales = 0;
    let totalCost = 0;
    let totalProfit = 0;
    
    const chartData: any[] = [];
    const groupedData: Record<string, { sales: number; cost: number; profit: number; count: number }> = {};

    (orders as any[]).forEach((order: any) => {
      // Calculate costs from items (if purchasePrice exists, otherwise fallback to 0 or product cost if joined)
      let orderCost = 0;
      order.items.forEach((item: any) => {
        const itemCost = (item.purchasePrice || 0) * item.quantity;
        orderCost += itemCost;
      });
      
      const orderSales = order.payableAmount; // or totalPrice depending on business logic
      const orderProfit = orderSales - orderCost;
      
      totalSales += orderSales;
      totalCost += orderCost;
      totalProfit += orderProfit;

      // Grouping key based on timeframe
      let groupKey = "";
      const d = new Date(order.createdAt);
      if (timeframe === "DAILY") {
        groupKey = d.getHours().toString().padStart(2, '0') + ":00"; // group by hour
      } else if (timeframe === "WEEKLY" || timeframe === "MONTHLY") {
        groupKey = format(d, "yyyy/MM/dd"); // group by day (Jalali)
      } else if (timeframe === "YEARLY") {
        groupKey = format(d, "yyyy/MM"); // group by month (Jalali)
      }

      if (!groupedData[groupKey]) {
        groupedData[groupKey] = { sales: 0, cost: 0, profit: 0, count: 0 };
      }
      
      groupedData[groupKey].sales += orderSales;
      groupedData[groupKey].cost += orderCost;
      groupedData[groupKey].profit += orderProfit;
      groupedData[groupKey].count += 1;
    });

    // Convert grouped data to array for chart
    for (const [key, data] of Object.entries(groupedData)) {
      chartData.push({
        name: key,
        فروش: data.sales,
        هزینه: data.cost,
        سود: data.profit,
        تعداد: data.count
      });
    }

    // Sort chart data by name (time)
    chartData.sort((a, b) => a.name.localeCompare(b.name));

    return { 
      success: true, 
      summary: {
        totalSales,
        totalCost,
        totalProfit,
        orderCount: orders.length
      },
      chartData 
    };
  } catch (err: any) {
    console.error("Error fetching reports:", err);
    return { success: false, error: err.message || "خطا در دریافت گزارشات" };
  }
}
