import prisma from "~/server/utils/prisma";

export default defineEventHandler(async (event) => {
  try {
    // Get current date and set to start of day
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    // Get yesterday
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    // Query counts for different job statuses
    const [failed, retrying, recovered, deadLetter] = await Promise.all([
      // Failed jobs count
      prisma.notification_queue.count({
        where: {
          status: "failed",
        },
      }),
      // Jobs currently being retried (if your system tracks this state)
      prisma.notification_queue.count({
        where: {
          status: "processing",
          attempts: {
            gt: 1,
          },
        },
      }),
      // Recovered jobs (failed but then succeeded)
      prisma.notification_queue.count({
        where: {
          status: "completed",
          attempts: {
            gt: 1,
          },
          updated_at: {
            gte: yesterday,
          },
        },
      }),
      // Dead letter queue (failed and max attempts reached)
      prisma.notification_queue.count({
        where: {
          status: "failed",
          attempts: {
            equals: prisma.notification_queue.fields.max_attempts,
          },
        },
      }),
    ]);

    return {
      success: true,
      data: {
        failed,
        retrying,
        recovered,
        deadLetter,
      },
    };
  } catch (error) {
    console.error("Error fetching retry stats:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to fetch retry statistics",
      data: {
        error: error.message,
      },
    });
  } finally {
  }
}); 