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

export default defineEventHandler(async (event) => {
  try {
    // Get job ID from params
    const id = event.context.params.id;

    if (!id) {
      throw createError({
        statusCode: 400,
        statusMessage: "Job ID is required",
      });
    }

    // Check if job exists and is in a failed state
    const job = await prisma.notification_queue.findUnique({
      where: {
        id: id,
      },
    });

    if (!job) {
      throw createError({
        statusCode: 404,
        statusMessage: "Job not found",
      });
    }

    if (job.status !== "failed") {
      throw createError({
        statusCode: 400,
        statusMessage: "Only failed jobs can be retried",
      });
    }

    // Reset job for retry
    await prisma.notification_queue.update({
      where: {
        id: id,
      },
      data: {
        status: "queued",
        attempts: job.attempts, // Keep the previous attempts count for tracking
        last_attempt_at: null,
        error_message: null,
        updated_at: new Date(),
      },
    });

    // Log the retry action
    await prisma.notification_logs.create({
      data: {
        notification_id: job.notification_id,
        action: "Job Retry",
        status: "Queued",
        details: `Job ${id} requeued for retry after ${job.attempts} previous attempts`,
        created_at: new Date(),
      },
    });

    return {
      success: true,
      data: {
        message: "Job queued for retry",
        jobId: id,
      },
    };
  } catch (error) {
    console.error("Error retrying job:", error);

    if (error.statusCode) {
      throw error;
    }

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