import { z } from 'zod'
import { validateBody } from '../../../utils/bodyValidation'
import { createFeedback } from '../../../database/queries/admin'
import { requireUserSession } from '../../../utils/auth'
import { handleApiError, createSuccessResponse } from '../../../utils/errors'

const schema = z.object({
  message: z.string().min(1, 'Message is required'),
  meta: z
    .object({
      browser: z.string().optional(),
      screenResolution: z.string().optional(),
      language: z.string().optional(),
      platform: z.string().optional(),
      colorScheme: z.string().optional(),
      timezone: z.string().optional(),
      url: z.string().optional()
    })
    .optional()
})

export default defineEventHandler(async (event) => {
  try {
    const session = await requireUserSession(event)
    const data = await validateBody(event, schema)

    const feedback = await createFeedback({
      userId: session.user.id,
      message: data.message,
      meta: data.meta
    })

    return createSuccessResponse(feedback, 'Feedback submitted successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
