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

export default defineEventHandler(async (event) => {
  try {
    // Get current user (assuming auth middleware provides this)
    const user = event.context.user;
    if (!user || !user.userID) {
      throw createError({
        statusCode: 401,
        statusMessage: "Authentication required",
      });
    }

    // Get queue statistics
    const queueStats = await prisma.notification_queue.groupBy({
      by: ['status'],
      _count: {
        status: true
      },
      orderBy: {
        status: 'asc'
      }
    });

    // Get recent queue items
    const recentItems = await prisma.notification_queue.findMany({
      include: {
        notifications: {
          select: {
            id: true,
            title: true,
            created_at: true,
            status: true
          }
        },
        notification_recipients: {
          select: {
            id: true,
            email: true,
            channel_type: true,
            status: true
          }
        }
      },
      orderBy: {
        created_at: 'desc'
      },
      take: 20
    });

    return {
      success: true,
      data: {
        stats: queueStats.reduce((acc, stat) => {
          acc[stat.status] = stat._count.status;
          return acc;
        }, {}),
        recentItems: recentItems.map(item => ({
          id: item.id,
          notificationTitle: item.notifications?.title,
          recipientEmail: item.notification_recipients?.email,
          channelType: item.notification_recipients?.channel_type,
          status: item.status,
          scheduledFor: item.scheduled_for,
          createdAt: item.created_at,
          lastAttempt: item.last_attempt_at,
          attempts: item.attempts,
          errorMessage: item.error_message
        }))
      }
    };
  } catch (error) {
    console.error('Error fetching queue status:', error);
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to fetch queue status',
      data: {
        error: error.message
      }
    });
  } finally {
  }
});