import { sendEmail } from '../../../utils/email'
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 ReplyFeedbackRequest {
  id: string
  message: string
  email: string
}

export default defineEventHandler(async (event) => {
  try {
    // Require super admin access
    const session = await requireSuperAdmin(event)

    const { id, message, email } = await readBody(event) as ReplyFeedbackRequest

    const feedback = await getFeedbackById(id)
    if (!feedback) {
      throw ApiErrors.notFound('Feedback not found')
    }

    await updateFeedback(id, { reply: message, status: 'replied' })

    // Create notification for the user who submitted the feedback
    if (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: 'replied to your support request',
        url: '/dashboard/account/support'
      })
    }

    const config = useRuntimeConfig()
    const htmlTemplate = await renderEmailComponent('feedback-reply', {
      userName: feedback.user.name,
      originalMessage: feedback.message,
      replyMessage: message,
      appName: config.appName || 'Harmonic SaaS',
      baseUrl: config.public?.betterAuthUrl || 'http://localhost:3000'
    })

    if (useRuntimeConfig().mockEmail === 'true') {
      console.table({
        email,
        name: feedback.user.name,
        originalMessage: feedback.message,
        replyMessage: message
      })
    } else {
      await sendEmail({
        to: email,
        subject: 'Response to your feedback',
        html: htmlTemplate
      })
    }

    return createSuccessResponse({ feedbackId: id }, 'Reply sent successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
