package infra

import "fmt"

// MetabaseExecuteQuery ejecuta una query ad-hoc (sin guardar como card) en Metabase.
// databaseID: ID de la base de datos en Metabase.
// sql: query SQL a ejecutar.
// maxResults: limite de filas (0 = default 2000 de Metabase).
func MetabaseExecuteQuery(client MetabaseClient, databaseID int, sql string, maxResults int) (map[string]any, error) {
	body := map[string]any{
		"database": databaseID,
		"type":     "native",
		"native":   map[string]any{"query": sql},
	}
	if maxResults > 0 {
		body["constraints"] = map[string]any{
			"max-results":          maxResults,
			"max-results-bare-rows": maxResults,
		}
	}

	result, err := metabaseRequest("POST", client.BaseURL, client.Token, "/api/dataset", body)
	if err != nil {
		return nil, fmt.Errorf("metabase execute query: %w", err)
	}

	return result, nil
}
