package database

import (
	"context"
	"database/sql"
	"log/slog"

	"git.savin.nyc/alex/go-receipt-tracker/config"
	"git.savin.nyc/alex/go-receipt-tracker/models"
	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/pgdialect"
	"github.com/uptrace/bun/driver/pgdriver"
	"github.com/uptrace/bun/extra/bundebug"
)

func NewDB(cfg *config.DataBase, log *slog.Logger) (*bun.DB, error) {
	ctx := context.Background()

	// dsn := "postgres://bun:bun@localhost:5432/bun?sslmode=disable"
	sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(cfg.DSN)))

	db := bun.NewDB(sqldb, pgdialect.New())
	db.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))

	// Register models before loading fixtures.
	db.RegisterModel((*models.GroupToUser)(nil), (*models.User)(nil), (*models.Group)(nil), (*models.Receipt)(nil), (*models.Merchant)(nil), (*models.CreditCard)(nil), (*models.Item)(nil), (*models.WhiteList)(nil), (*models.BlackList)(nil))

	models := []interface{}{
		(*models.User)(nil),
		(*models.Group)(nil),
		(*models.GroupToUser)(nil),
		(*models.Receipt)(nil),
		(*models.Merchant)(nil),
		(*models.CreditCard)(nil),
		(*models.Item)(nil),
		(*models.WhiteList)(nil),
		(*models.BlackList)(nil),
		// (*models.Settings)(nil),
	}

	for _, model := range models {
		if _, err := db.NewCreateTable().Model(model).Exec(ctx); err != nil {
			continue
		}
	}

	return db, nil
}
