package db

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"trustcontact/internal/config"

	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	gormlogger "gorm.io/gorm/logger"
)

func Open(cfg *config.Config) (*gorm.DB, error) {
	if cfg == nil {
		return nil, fmt.Errorf("config is nil")
	}

	gormCfg := &gorm.Config{Logger: newLogger(cfg.Env)}

	switch cfg.DBDriver {
	case config.DBDriverSQLite:
		if err := ensureSQLiteDir(cfg.SQLitePath); err != nil {
			return nil, fmt.Errorf("prepare sqlite dir: %w", err)
		}
		return gorm.Open(sqlite.Open(cfg.SQLitePath), gormCfg)
	case config.DBDriverPostgres:
		return gorm.Open(postgres.Open(cfg.PostgresDSN), gormCfg)
	default:
		return nil, fmt.Errorf("unsupported db driver: %s", cfg.DBDriver)
	}
}

func newLogger(env string) gormlogger.Interface {
	level := gormlogger.Warn
	if env == config.EnvDevelop {
		level = gormlogger.Info
	}

	return gormlogger.Default.LogMode(level)
}

func ensureSQLiteDir(sqlitePath string) error {
	dir := filepath.Dir(sqlitePath)
	if dir == "." || dir == "" {
		return nil
	}

	return os.MkdirAll(dir, 0o755)
}

func nowUTC() time.Time {
	return time.Now().UTC()
}
