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

export default defineEventHandler(async (event) => {
  try {
    // Get notification ID from route parameters
    const notificationId = getRouterParam(event, 'id')
    
    if (!notificationId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Notification ID is required'
      })
    }

    // Get current user (assuming auth middleware provides this)
    const user = event.context.user
    if (!user || !user.userID) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Authentication required'
      })
    }

    // Use Prisma transaction
    const result = await prisma.$transaction(async (tx) => {
      // First, check if the notification exists and belongs to the user
      const notification = await tx.notifications.findFirst({
        where: {
          id: notificationId,
          created_by: user.userID.toString()
        },
        select: {
          id: true,
          title: true,
          status: true
        }
      });
      
      if (!notification) {
        throw createError({
          statusCode: 404,
          statusMessage: 'Notification not found or you do not have permission to delete it'
        })
      }

      // Check if notification can be deleted (only draft, scheduled, failed, or cancelled notifications)
      const deletableStatuses = ['draft', 'scheduled', 'failed', 'cancelled']
      if (!deletableStatuses.includes(notification.status)) {
        const statusMessage = notification.status === 'sending' 
          ? `Cannot delete notification while it's being sent. Please wait for it to complete or fail, then try again.`
          : notification.status === 'sent'
          ? `Cannot delete notification that has already been sent. Sent notifications are kept for audit purposes.`
          : `Cannot delete notification with status: ${notification.status}. Only draft, scheduled, failed, or cancelled notifications can be deleted.`;
        
        throw createError({
          statusCode: 400,
          statusMessage: statusMessage
        })
      }

      // If notification was scheduled, remove it from queue first
      if (notification.status === 'scheduled') {
        await tx.notification_queue.deleteMany({
          where: {
            notification_id: notificationId
          }
        });
      }

      // Delete related records first (if not handled by CASCADE)
      await tx.notification_recipients.deleteMany({
        where: {
          notification_id: notificationId
        }
      });

      await tx.notification_channels.deleteMany({
        where: {
          notification_id: notificationId
        }
      });

      await tx.notification_user_segments.deleteMany({
        where: {
          notification_id: notificationId
        }
      });

      // Delete the notification
      const deletedNotification = await tx.notifications.delete({
        where: {
          id: notificationId
        }
      });

      return {
        id: deletedNotification.id,
        title: notification.title
      };
    });

    return {
      success: true,
      data: {
        id: result.id,
        title: result.title,
        message: 'Notification deleted successfully'
      }
    }

  } catch (error) {
    console.error('Error deleting notification:', error)
    
    if (error.statusCode) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to delete notification',
      data: {
        error: error.message
      }
    })
  } finally {
  }
}) 