import { prisma } from '@/lib/prisma';
import { cleanupPendingOrders } from '@/lib/cleanupOrders';
import AdminNotificationsBadge from './AdminNotificationsBadge';

export default async function AdminNotifications() {
  try {
    // Clean up old incomplete orders (older than 24 hours)
    await cleanupPendingOrders();

    // Only count pending orders that are less than 24 hours old (still waiting for payment)
    const recentThreshold = new Date(Date.now() - 24 * 60 * 60 * 1000);
    const [
      pendingOrders,
      designApprovalsInReview,
      photoRequests,
      unreadMessages,
    ] = await Promise.all([
      prisma.order.count({
        where: {
          OR: [
            {
              status: 'PENDING',
              archived: false,
              createdAt: { gte: recentThreshold },
            },
            {
              status: 'PAID',
              archived: false,
              trackingNumber: null,
            },
          ],
        },
      }),
      prisma.designApproval.count({
        where: { status: { in: ['PENDING', 'IN_REVIEW'] } },
      }),
      prisma.customRequest.count({
        where: { status: 'PENDING' },
      }),
      prisma.message.count({
        where: { isRead: false },
      }),
    ]);

    const totalNotifications = pendingOrders + designApprovalsInReview + photoRequests + unreadMessages;

    return (
      <AdminNotificationsBadge
        total={totalNotifications}
        pendingOrders={pendingOrders}
        designApprovals={designApprovalsInReview}
        photoRequests={photoRequests}
        unreadMessages={unreadMessages}
      />
    );
  } catch (err) {
    console.error('Error fetching admin notifications:', err);
    return <AdminNotificationsBadge total={0} pendingOrders={0} designApprovals={0} photoRequests={0} unreadMessages={0} />;
  }
}
