import { requireSuperAdmin } from '../../../utils/auth'
import { setSiteConfig } from '../../../database/queries/siteconfig'
import { handleApiError, createSuccessResponse } from '../../../utils/errors'
import { z } from 'zod'
import { validateBody } from '../../../utils/bodyValidation'

const configSchema = z.object({
  key: z.string().min(1),
  value: z.string(),
  description: z.string().optional()
})

interface SetSiteConfigResponse {
  key: string
  value: string
  description?: string
}

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

    const body = await validateBody(event, configSchema)
    const { key, value, description } = body

    const result = await setSiteConfig(key, value, description)

    return createSuccessResponse<SetSiteConfigResponse>(result[0] as SetSiteConfigResponse, 'Site config updated successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
