import { requireSuperAdmin } from '../../../utils/auth'
import { useDB, eq } from '../../../utils/database'
import { user as userTable } from '../../../database/schema'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../../utils/errors'

interface DeleteUserRequest {
  userId: string
}

interface DeleteUserResponse {
  userId: string
  deleted: boolean
}

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

    const body = await readBody(event) as DeleteUserRequest
    if (!body.userId) {
      throw ApiErrors.validationError('User ID is required')
    }

    const [userRecord] = await useDB()
      .delete(userTable)
      .where(eq(userTable.id, body.userId))
      .returning()

    if (!userRecord) {
      throw ApiErrors.notFound('User not found')
    }

    return createSuccessResponse<DeleteUserResponse>({
      userId: body.userId,
      deleted: true
    }, 'User deleted successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
