package main

import (
	"context"
	"database/sql"
	"fmt"

	"git.haelnorr.com/h/oslstats/internal/config"
	"git.haelnorr.com/h/oslstats/internal/db"
	"github.com/pkg/errors"
	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/pgdialect"
	"github.com/uptrace/bun/driver/pgdriver"
)

func setupBun(ctx context.Context, cfg *config.Config) (conn *bun.DB, close func() error, err error) {
	dsn := fmt.Sprintf("postgres://%s:%s@%s:%v/%s?sslmode=%s",
		cfg.DB.User, cfg.DB.Password, cfg.DB.Host, cfg.DB.Port, cfg.DB.DB, cfg.DB.SSL)
	sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
	conn = bun.NewDB(sqldb, pgdialect.New())
	close = sqldb.Close

	// Simple table creation for backward compatibility
	err = loadModels(ctx, conn)
	if err != nil {
		return nil, nil, errors.Wrap(err, "loadModels")
	}

	return conn, close, nil
}

func loadModels(ctx context.Context, conn *bun.DB) error {
	models := []any{
		(*db.User)(nil),
		(*db.DiscordToken)(nil),
	}

	for _, model := range models {
		_, err := conn.NewCreateTable().
			Model(model).
			IfNotExists().
			Exec(ctx)
		if err != nil {
			return errors.Wrap(err, "db.NewCreateTable")
		}
	}

	return nil
}
