'use server';

import { prisma } from './prisma';

export async function getAdminStats() {
  try {
    const totalRevenueData = await prisma.order.aggregate({
      _sum: { total: true },
      // Count revenue for valid non-failed orders
      where: { status: { notIn: ['cancelled'] } }
    });
    const totalOrders = await prisma.order.count();
    const totalProducts = await prisma.product.count();
    const totalUsers = await prisma.user.count();

    return {
      revenue: totalRevenueData._sum.total || 0,
      orders: totalOrders,
      products: totalProducts,
      users: totalUsers
    };
  } catch (err) {
    return { revenue: 0, orders: 0, products: 0, users: 0 };
  }
}

export async function getAdminRecentOrders() {
  try {
    const orders = await prisma.order.findMany({
      take: 20,
      orderBy: { createdAt: 'desc' },
      include: { items: true }
    });
    return orders;
  } catch (err) {
    return [];
  }
}

export async function getAdminProducts() {
  try {
    const products = await prisma.product.findMany({
      orderBy: { createdAt: 'desc' },
      include: { category: true }
    });
    return products;
  } catch (err) {
    return [];
  }
}
