import { requireSuperAdmin } from '../../../utils/auth'
import { createUser } from '../../../database/queries/users'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../../utils/errors'

interface CreateUserRequest {
  email: string
  name: string
}

interface CreateUserResponse {
  id: string
}

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

    const body = await readBody<CreateUserRequest>(event)
    if (!body?.email || !body?.name) {
      throw ApiErrors.validationError('Missing email or name')
    }

    const id = await createUser({ email: body.email, name: body.name })

    return createSuccessResponse<CreateUserResponse>({ id }, 'User created successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
