package main

import (
	"context"
	"fmt"
	"os"

	"git.haelnorr.com/h/oslstats/internal/config"
	"github.com/pkg/errors"
)

func main() {
	flags, err := config.SetupFlags()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error parsing flags: %v\n", err)
		os.Exit(1)
	}

	ctx := context.Background()

	cfg, loader, err := config.GetConfig(flags)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", errors.Wrap(err, "Failed to load config"))
		os.Exit(1)
	}

	// Handle utility flags
	if flags.EnvDoc || flags.ShowEnv {
		loader.PrintEnvVarsStdout(flags.ShowEnv)
		return
	}

	if flags.GenEnv != "" {
		loader.GenerateEnvFile(flags.GenEnv, true)
		return
	}

	// Handle migration file creation (doesn't need DB connection)
	if flags.MigrateCreate != "" {
		if err := createMigration(flags.MigrateCreate); err != nil {
			fmt.Fprintf(os.Stderr, "Error creating migration: %v\n", err)
			os.Exit(1)
		}
		return
	}

	// Handle commands that need database connection
	if flags.MigrateUp || flags.MigrateRollback ||
		flags.MigrateStatus || flags.MigrateDryRun ||
		flags.ResetDB {

		// Setup database connection
		conn, close, err := setupBun(ctx, cfg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error setting up database: %v\n", err)
			os.Exit(1)
		}
		defer close()

		// Route to appropriate command
		if flags.MigrateUp {
			err = runMigrations(ctx, conn, cfg, "up")
		} else if flags.MigrateRollback {
			err = runMigrations(ctx, conn, cfg, "rollback")
		} else if flags.MigrateStatus {
			err = runMigrations(ctx, conn, cfg, "status")
		} else if flags.MigrateDryRun {
			err = runMigrations(ctx, conn, cfg, "dry-run")
		} else if flags.ResetDB {
			err = resetDatabase(ctx, conn)
		}

		if err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		return
	}

	// Normal server startup
	if err := run(ctx, os.Stdout, cfg); err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
		os.Exit(1)
	}
}
