package data

import (
	"database/sql"
	"fmt"
	"sync"

	legacycfg "weatherstation/internal/config"

	_ "github.com/lib/pq"
)

var (
	dbOnce sync.Once
	dbInst *sql.DB
)

// DB returns a shared Postgres connection opened using legacy internal/config.
func DB() *sql.DB {
	dbOnce.Do(func() {
		cfg := legacycfg.GetConfig().Database
		connStr := fmt.Sprintf(
			"host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
			cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, cfg.SSLMode,
		)
		d, err := sql.Open("postgres", connStr)
		if err != nil {
			panic(fmt.Errorf("open DB failed: %w", err))
		}
		if err := d.Ping(); err != nil {
			panic(fmt.Errorf("ping DB failed: %w", err))
		}
		dbInst = d
	})
	if dbInst == nil {
		panic("database not initialized: check config and drivers")
	}
	return dbInst
}
