import { deleteFeedback, getFeedbackById } from '../../../database/queries/admin'
import { sendNotification } from '../../../utils/notifications'
import { requireSuperAdmin } from '../../../utils/auth'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../../utils/errors'

interface DeleteFeedbackResponse {
  feedbackId: string
  deleted: boolean
}

export default defineEventHandler(async (event) => {
  try {
    const session = await requireSuperAdmin(event)

    const { id } = getRouterParams(event)
    if (!id) {
      throw ApiErrors.validationError('Feedback ID is required')
    }

    // Get feedback details before deleting to notify the user
    const feedback = await getFeedbackById(id)
    if (!feedback) {
      throw ApiErrors.notFound('Feedback not found')
    }

    if (feedback.userId && session.user.name && session.user.email) {
      // Create notification for the user
      await sendNotification({
        userId: feedback.userId,
        senderName: session.user.name,
        senderEmail: session.user.email,
        senderAvatar: session.user.image ?? undefined,
        body: 'closed your support request',
        url: '/dashboard/account/support'
      })
    }

    await deleteFeedback(id)

    return createSuccessResponse<DeleteFeedbackResponse>({
      feedbackId: id,
      deleted: true
    }, 'Feedback deleted successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
