package main

import (
	"context"
	"flag"
	"log/slog"
	"os"

	"aigateway.local/core/internal/platform/config"
	"aigateway.local/core/internal/platform/database"
	"aigateway.local/core/internal/platform/migrate"
)

func main() {
	directory := flag.String("dir", "migrations", "directory containing ordered SQL migrations")
	flag.Parse()
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	cfg, err := config.Load()
	if err != nil {
		logger.Error("invalid configuration", "error", err)
		os.Exit(1)
	}
	if cfg.Database.URL == "" {
		logger.Error("DATABASE_URL is required by the migrator")
		os.Exit(1)
	}
	ctx := context.Background()
	pool, err := database.Open(ctx, cfg.Database)
	if err != nil {
		logger.Error("database initialization failed", "error", err)
		os.Exit(1)
	}
	defer pool.Close()
	migrations, err := migrate.Load(*directory)
	if err != nil {
		logger.Error("migration loading failed", "error", err)
		os.Exit(1)
	}
	if err := migrate.Apply(ctx, pool, migrations); err != nil {
		logger.Error("migration failed", "error", err)
		os.Exit(1)
	}
	logger.Info("migrations complete", "count", len(migrations))
}
