import { getUserById, updateUser } from '../../../database/queries/users'
import { validateBody } from '../../../utils/bodyValidation'
import { requireSuperAdmin } from '../../../utils/auth'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../../utils/errors'
import { z } from 'zod'

const schema = z.object({
  banned: z.boolean(),
  userId: z.string().min(1, 'User ID is required'),
  reason: z.string().optional(),
  bannedUntil: z.string().optional()
})

interface BanUserResponse {
  userId: string
  banned: boolean
  message: string
}

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

    // Validate the request body
    const body = await validateBody(event, schema)
    const { userId, banned, reason, bannedUntil } = body

    const userRecord = await getUserById(userId)
    if (!userRecord) {
      throw ApiErrors.notFound('User not found')
    }

    const bannedUntilDate = bannedUntil ? new Date(bannedUntil) : null
    await updateUser(userId, {
      banned,
      bannedReason: banned ? (reason ?? null) : null,
      bannedUntil: banned ? bannedUntilDate : null
    })

    return createSuccessResponse<BanUserResponse>({
      userId,
      banned,
      message: banned ? 'User banned successfully' : 'Ban lifted successfully'
    })
  } catch (error) {
    throw handleApiError(error)
  }
})
