/**
 * Get all clients from Metabase
 * Uses "Clientes - Lista Simple" query (ID: 55)
 * Returns: id, name, ubicacion, cedula for use in filters
 */
export default defineEventHandler(async () => {
  try {
    // Get all cards to find the clientes query
    const allCards = await getMetabaseCards('all')

    // Find "Clientes - Lista Simple" query
    const card = allCards.find((c: any) => c.name === 'Clientes - Lista Simple')

    if (!card) {
      console.error('[API] Clientes query not found in Metabase')
      throw createError({
        statusCode: 404,
        statusMessage: 'Clientes query not found in Metabase'
      })
    }

    console.log('[API] Found clientes card:', card.id, card.name)

    // Execute the query (no parameters needed - it's a simple SELECT)
    const result = await executeCardQuery(card.id, [])

    console.log('[API] Clientes query result:', {
      hasData: !!result.data,
      rows: result.data?.rows?.length,
      cols: result.data?.cols?.length,
      firstRow: result.data?.rows?.[0]
    })

    if (!result.data?.rows || !result.data?.cols) {
      console.warn('[API] No data returned from clientes query')
      return []
    }

    // Transform rows to objects with only the fields we need
    const cols = result.data.cols
    const clientes = result.data.rows.map((row: any[]) => {
      const obj: any = {}
      cols.forEach((col: any, index: number) => {
        obj[col.name] = row[index]
      })

      // Return only the fields needed for the selector
      return {
        id: obj.cliente_id,
        name: obj.cliente_nombre,
        ubicacion: obj.cliente_ubicacion,
        cedula: obj.cliente_cedula
      }
    })

    console.log('[API] Transformed clientes:', clientes.length, 'records')

    // Already sorted by nombre in SQL query, but return as-is
    return clientes
  } catch (error: any) {
    console.error('[API] Failed to fetch clientes from Metabase:', error)
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || 'Failed to fetch clientes from Metabase'
    })
  }
})
