package db

import (
	"context"
	"time"

	"git.kanopo.dev/rhythm/rhythm-backend/internal/config"
	"github.com/jackc/pgx/v5/pgxpool"
	"go.uber.org/fx"
	"go.uber.org/zap"
)

func ProvidePool(lc fx.Lifecycle, cfg *config.Config, log *zap.SugaredLogger) (*pgxpool.Pool, error) {
	ctx := context.Background()
	pool, err := pgxpool.New(ctx, cfg.DbUrl)
	if err != nil {
		return nil, err
	}

	{
		ctx, cancel := context.WithTimeout(ctx, time.Second*5)
		defer cancel()
		if err := pool.Ping(ctx); err != nil {
			return nil, err
		}
		log.Info("successfully connected to database")
		RunMigrations(cfg.DbUrl, log)
	}

	lc.Append(fx.Hook{
		OnStop: func(ctx context.Context) error {
			log.Info("Closing database pool")
			pool.Close()
			return nil
		},
	})

	return pool, nil
}
