package database

import (
	"fmt"
	"time"

	"api-soap-facturacion/internal/config"
	_ "github.com/jackc/pgx/v5/stdlib"
	"github.com/jmoiron/sqlx"
)

// NewPostgresConnection crea una nueva conexión a PostgreSQL
func NewPostgresConnection(cfg config.DatabaseConfig) (*sqlx.DB, error) {
	dsn := fmt.Sprintf(
		"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		cfg.Host, cfg.Port, cfg.Username, cfg.Password, cfg.Database,
	)

	db, err := sqlx.Connect("pgx", dsn)
	if err != nil {
		return nil, err
	}

	// Configurar pool de conexiones
	db.SetMaxOpenConns(cfg.MaxOpenConns)
	db.SetMaxIdleConns(cfg.MaxIdleConns)
	db.SetConnMaxLifetime(cfg.ConnMaxLifetime * time.Hour)

	return db, nil
}

// LoadParameters carga parámetros desde la base de datos
func LoadParameters(db *sqlx.DB) (map[string]string, error) {
	var params []Parameter
	query := `SELECT id, key, value, description, created_at, updated_at FROM parameters WHERE active = true`

	err := db.Select(&params, query)
	if err != nil {
		return nil, err
	}

	// Convertir a map
	result := make(map[string]string)
	for _, param := range params {
		result[param.Key] = param.Value
	}

	return result, nil
}
