import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { cleanupPendingOrders } from '@/lib/cleanupOrders';

export async function GET() {
  try {
    await cleanupPendingOrders();

    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 NextResponse.json({
      total: totalNotifications,
      pendingOrders,
      designApprovals: designApprovalsInReview,
      photoRequests,
      unreadMessages,
    });
  } catch (err) {
    console.error('Error fetching admin notifications:', err);
    return NextResponse.json({
      total: 0,
      pendingOrders: 0,
      designApprovals: 0,
      photoRequests: 0,
      unreadMessages: 0,
    });
  }
}
