package main

import (
	"context"
	"log/slog"
	"net/url"
	"os"
	"time"

	"github.com/jackc/pgx/v5"

	"git.toki-labs.com/toki/alt/services/worker/internal/config"
	"git.toki-labs.com/toki/alt/services/worker/internal/storage/postgres"
)

// redactDatabaseURL parses and redacts the password from a database URL connection string.
func redactDatabaseURL(rawURL string) string {
	u, err := url.Parse(rawURL)
	if err != nil {
		return "[invalid database url]"
	}
	if u.User != nil {
		if _, hasPassword := u.User.Password(); hasPassword {
			u.User = url.UserPassword(u.User.Username(), "xxxxx")
		}
	}
	return u.String()
}

func main() {
	cfg := config.Load()

	slog.Info("starting migrations", "database_url", redactDatabaseURL(cfg.DatabaseURL))

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	conn, err := pgx.Connect(ctx, cfg.DatabaseURL)
	if err != nil {
		slog.Error("failed to connect to database", "error", err)
		os.Exit(1)
	}
	defer conn.Close(ctx)

	err = postgres.RunMigrations(ctx, conn)
	if err != nil {
		slog.Error("failed to run migrations", "error", err)
		os.Exit(1)
	}

	slog.Info("migrations completed successfully")
}
