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",
      });
    }

    const body = await readBody(event);
    const { action = 'failed_only' } = body; // 'failed_only', 'completed_only', 'all_old'

    let whereCondition = {};

    switch (action) {
      case 'failed_only':
        whereCondition = {
          status: 'failed'
        };
        break;
      case 'completed_only':
        whereCondition = {
          status: 'completed'
        };
        break;
      case 'all_old':
        // Clear items older than 1 hour except queued ones
        whereCondition = {
          created_at: {
            lt: new Date(Date.now() - 60 * 60 * 1000) // 1 hour ago
          },
          status: {
            not: 'queued'
          }
        };
        break;
      case 'all_except_latest':
        // Get the latest notification ID first
        const latestNotification = await prisma.notifications.findFirst({
          orderBy: { created_at: 'desc' },
          select: { id: true }
        });
        
        if (latestNotification) {
          whereCondition = {
            notification_id: {
              not: latestNotification.id
            },
            status: {
              in: ['failed', 'completed']
            }
          };
        }
        break;
      default:
        throw createError({
          statusCode: 400,
          statusMessage: "Invalid action. Use: failed_only, completed_only, all_old, all_except_latest"
        });
    }

    // Delete queue items based on condition
    const deleteResult = await prisma.notification_queue.deleteMany({
      where: whereCondition
    });

    return {
      success: true,
      data: {
        message: `Cleared ${deleteResult.count} queue items`,
        action,
        deletedCount: deleteResult.count
      }
    };
  } catch (error) {
    console.error('Error clearing queue:', error);
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to clear queue',
      data: {
        error: error.message
      }
    });
  } finally {
  }
});