package config

import (
	"flag"

	"github.com/pkg/errors"
)

type Flags struct {
	// Utility flags
	EnvDoc  bool
	ShowEnv bool
	GenEnv  string
	EnvFile string
	HTMXLog bool

	// Database reset (destructive)
	ResetDB bool

	// Migration commands
	MigrateUp       bool
	MigrateRollback bool
	MigrateStatus   bool
	MigrateCreate   string
	MigrateDryRun   bool

	// Backup control
	MigrateNoBackup bool
}

func SetupFlags() (*Flags, error) {
	// Utility flags
	envDoc := flag.Bool("envdoc", false, "Print all environment variables and their documentation")
	showEnv := flag.Bool("showenv", false, "Print all environment variable values and their documentation")
	genEnv := flag.String("genenv", "", "Generate a .env file with all environment variables (specify filename)")
	envfile := flag.String("envfile", ".env", "Specify a .env file to use for the configuration")
	htmxlog := flag.Bool("htmxlog", false, "Run the server with all HTMX events logged")

	// Database reset (destructive)
	resetDB := flag.Bool("reset-db", false, "⚠️  DESTRUCTIVE: Drop and recreate all tables (dev only)")

	// Migration commands
	migrateUp := flag.Bool("migrate-up", false, "Run pending database migrations (with automatic backup)")
	migrateRollback := flag.Bool("migrate-rollback", false, "Rollback the last migration group (with automatic backup)")
	migrateStatus := flag.Bool("migrate-status", false, "Show database migration status")
	migrateCreate := flag.String("migrate-create", "", "Create a new migration file with the given name")
	migrateDryRun := flag.Bool("migrate-dry-run", false, "Preview pending migrations without applying them")

	// Backup control
	migrateNoBackup := flag.Bool("no-backup", false, "Skip automatic backups (dev only - faster but less safe)")

	flag.Parse()

	// Validate: can't use multiple migration commands at once
	commands := 0
	if *migrateUp {
		commands++
	}
	if *migrateRollback {
		commands++
	}
	if *migrateStatus {
		commands++
	}
	if *migrateDryRun {
		commands++
	}
	if *resetDB {
		commands++
	}

	if commands > 1 {
		return nil, errors.New("cannot use multiple migration commands simultaneously")
	}

	flags := &Flags{
		EnvDoc:          *envDoc,
		ShowEnv:         *showEnv,
		GenEnv:          *genEnv,
		EnvFile:         *envfile,
		HTMXLog:         *htmxlog,
		ResetDB:         *resetDB,
		MigrateUp:       *migrateUp,
		MigrateRollback: *migrateRollback,
		MigrateStatus:   *migrateStatus,
		MigrateCreate:   *migrateCreate,
		MigrateDryRun:   *migrateDryRun,
		MigrateNoBackup: *migrateNoBackup,
	}
	return flags, nil
}
