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

interface UsersListResponse {
  users: unknown[]
  page: number
  pageSize: number
  total: number
}

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

    // Use pagination utility
    const query = getQuery(event)
    const paginationParams = createPaginationParams(query)

    // Parse filter parameters
    const role = (query.role as string) || 'all'
    const emailVerified = (query.emailVerified as string) || 'all'
    const banned = (query.banned as string) || 'all'
    const subscription = (query.subscription as string) || 'all'
    const provider = (query.provider as string) || 'all'

    const { users, total } = await listUsersWithTotal({
      page: paginationParams.page,
      pageSize: paginationParams.pageSize,
      role: role as 'all' | 'admin' | 'user',
      emailVerified: emailVerified as 'all' | 'verified' | 'unverified',
      banned: banned as 'all' | 'banned' | 'active',
      subscription: subscription, // Can be 'all', 'active', 'none', a product ID, or comma-separated product IDs
      provider: provider as 'all' | 'credential' | 'github' | 'google'
    })

    return createSuccessResponse<UsersListResponse>({
      users,
      page: paginationParams.page,
      pageSize: paginationParams.pageSize,
      total
    })
  } catch (error) {
    throw handleApiError(error)
  }
})
