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

export default defineEventHandler(async (event) => {
  try {
    // Find all failed jobs
    const failedJobs = await prisma.notification_queue.findMany({
      where: {
        status: "failed",
      },
      select: {
        id: true,
        notification_id: true,
        attempts: true,
      },
    });

    if (failedJobs.length === 0) {
      return {
        success: true,
        data: {
          message: "No failed jobs to retry",
          count: 0,
        },
      };
    }

    // Update all failed jobs to queued status
    await prisma.notification_queue.updateMany({
      where: {
        status: "failed",
      },
      data: {
        status: "queued",
        last_attempt_at: null,
        error_message: null,
        updated_at: new Date(),
      },
    });

    // Log the batch retry action
    await prisma.notification_logs.create({
      data: {
        action: "Batch Job Retry",
        status: "Processed",
        details: `${failedJobs.length} failed jobs requeued for retry`,
        created_at: new Date(),
      },
    });

    return {
      success: true,
      data: {
        message: `${failedJobs.length} jobs queued for retry`,
        count: failedJobs.length,
      },
    };
  } catch (error) {
    console.error("Error retrying all failed jobs:", error);

    if (error.statusCode) {
      throw error;
    }

    throw createError({
      statusCode: 500,
      statusMessage: "Failed to retry all jobs",
      data: {
        error: error.message,
      },
    });
  } finally {
  }
}); 