/**
 * Execute a query against Metabase
 */
export default defineEventHandler(async (event) => {
  const body = await readBody(event)

  const { databaseId, tableId, query } = body

  if (!databaseId || !tableId) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Database ID and Table ID are required'
    })
  }

  try {
    const result = await queryMetabaseTable(
      parseInt(databaseId),
      parseInt(tableId),
      query
    )
    return result
  } catch (error: any) {
    console.error('[API] Failed to execute Metabase query:', error)
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || 'Failed to execute query'
    })
  }
})
