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

interface UpdateFeedbackRequest {
  status: string
}

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

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

    const { status } = await readBody<UpdateFeedbackRequest>(event)

    // Get feedback details before updating to check if status changed to closed
    const feedback = await getFeedbackById(id)
    if (!feedback) {
      throw ApiErrors.notFound('Feedback not found')
    }

    // Update the feedback
    const updatedFeedback = await updateFeedback(id, { status })

    // If status is being changed to "closed", notify the user
    if (status === 'closed' && feedback.userId && session.user.name && session.user.email) {
      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'
      })
    }

    return createSuccessResponse(updatedFeedback, 'Feedback updated successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
