package infra

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// MetabaseAuth autentica con email y password contra una instancia Metabase.
// Retorna un MetabaseClient con el session token listo para usar.
// baseURL es la URL base sin trailing slash (ej: "http://localhost:3000").
func MetabaseAuth(baseURL, email, password string) (MetabaseClient, error) {
	payload, _ := json.Marshal(map[string]string{
		"username": email,
		"password": password,
	})

	resp, err := http.Post(baseURL+"/api/session", "application/json", bytes.NewReader(payload))
	if err != nil {
		return MetabaseClient{}, fmt.Errorf("metabase auth: %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return MetabaseClient{}, fmt.Errorf("read auth response: %w", err)
	}

	if resp.StatusCode != 200 {
		return MetabaseClient{}, fmt.Errorf("metabase auth: status %d: %s", resp.StatusCode, string(body))
	}

	var result struct {
		ID string `json:"id"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		return MetabaseClient{}, fmt.Errorf("parse auth response: %w", err)
	}

	return MetabaseClient{BaseURL: baseURL, Token: result.ID}, nil
}

// MetabaseNewClient crea un MetabaseClient usando una API key en lugar de session token.
// Las API keys se crean en Settings > Authentication > API Keys del admin de Metabase.
func MetabaseNewClient(baseURL, apiKey string) MetabaseClient {
	return MetabaseClient{BaseURL: baseURL, Token: apiKey}
}
