import prisma from "~/server/utils/prisma"; export default defineEventHandler(async (event) => { try { // Get current user from auth middleware const user = event.context.user; if (!user) { throw createError({ statusCode: 401, statusMessage: "Authentication required", }); } // Get query parameters const query = getQuery(event); const limit = parseInt(query.limit) || 10; const page = parseInt(query.page) || 1; const status = query.status; // Build where clause const where = {}; if (status) { where.status = status; } // Get jobs with related data const jobs = await prisma.notification_queue.findMany({ where, select: { id: true, status: true, scheduled_for: true, last_attempt_at: true, error_message: true, notifications: { select: { type: true, title: true, } }, notification_recipients: { select: { channel_type: true, } } }, orderBy: { scheduled_for: 'desc' }, skip: (page - 1) * limit, take: limit }); // Format jobs for frontend const formattedJobs = jobs.map(job => { const timeDiff = new Date() - new Date(job.last_attempt_at || job.scheduled_for); const minutes = Math.floor(timeDiff / 60000); return { id: job.id, type: job.notifications.type, description: job.notifications.title, status: job.status, time: minutes <= 0 ? 'Just now' : minutes === 1 ? '1 minute ago' : minutes < 60 ? `${minutes} minutes ago` : `${Math.floor(minutes / 60)} hours ago` }; }); // Get total count for pagination const total = await prisma.notification_queue.count({ where }); return { success: true, data: { jobs: formattedJobs, pagination: { page, totalPages: Math.ceil(total / limit), totalItems: total, hasMore: page * limit < total } } }; } catch (error) { console.error('Error fetching queue jobs:', error); if (error.statusCode) { throw error; } throw createError({ statusCode: 500, statusMessage: 'Failed to fetch queue jobs' }); } finally { await prisma.$disconnect(); } });