package db

import (
	"database/sql"
	"log"

	"git.kanopo.dev/rhythm/rhythm-backend/internal/logger"
	"git.kanopo.dev/rhythm/rhythm-backend/migrations"
	_ "github.com/jackc/pgx/v5/stdlib"
	"github.com/pressly/goose/v3"
	"go.uber.org/zap"
)

func RunMigrations(dbURL string, zLog *zap.SugaredLogger) {
	db, err := sql.Open("pgx", dbURL)
	if err != nil {
		log.Fatalf("open db for migrations: %v", err.Error())
	}
	defer db.Close()

	goose.SetLogger(&logger.GooseLogger{SugaredLogger: zLog})

	// 2. Pass the exported FS to Goose!
	goose.SetBaseFS(migrations.FS)
	if err := goose.SetDialect("postgres"); err != nil {
		log.Fatalf("set goose dialect: %v", err.Error())
	}

	// 3. Run the migrations using the current directory "." of the embed.FS
	if err := goose.Up(db, "."); err != nil {
		log.Fatalf("run goose up: %v", err.Error())
	}
}
