import { requireSuperAdmin } from '../../../utils/auth'
import { useDB } from '../../../utils/database'
import { handleApiError, createSuccessResponse } from '../../../utils/errors'

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

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const db = useDB() as any
    const teams = await db.query.teams?.findMany({
      with: {
        owner: true,
        subscription: {
          columns: {
            id: true,
            status: true
          },
          with: {
            price: true
          }
        },
        members: {
          with: {
            user: {
              columns: {
                id: true,
                name: true,
                email: true,
                avatarUrl: true
              }
            }
          }
        }
      },
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      orderBy: (_teams: any, { desc }: any) => [desc(_teams.createdAt)],
      limit: 20,
      offset: 0
    })

    return createSuccessResponse(teams || [], 'Teams retrieved successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
