package main

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

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

func main() {
	adminUsername := flag.String("admin-username", env("BOOTSTRAP_ADMIN_USERNAME", "admin"), "initial administrator username")
	adminDisplayName := flag.String("admin-display-name", "系统管理员", "initial administrator display name")
	portalAccount := flag.String("portal-account", strings.TrimSpace(os.Getenv("BOOTSTRAP_PORTAL_ACCOUNT")), "optional initial portal account")
	portalName := flag.String("portal-name", "初始用户", "initial portal user display name")
	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")
		os.Exit(1)
	}
	adminPassword := os.Getenv("BOOTSTRAP_ADMIN_PASSWORD")
	portalPassword := os.Getenv("BOOTSTRAP_PORTAL_PASSWORD")
	if len(adminPassword) < 12 {
		logger.Error("BOOTSTRAP_ADMIN_PASSWORD must contain at least 12 characters")
		os.Exit(1)
	}
	if *portalAccount != "" && len(portalPassword) < 12 {
		logger.Error("BOOTSTRAP_PORTAL_PASSWORD must contain at least 12 characters when creating a portal user")
		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()
	repository := identity.NewRepository(pool)
	hasher := identity.PasswordHasher{}
	adminHash, err := hasher.Hash(adminPassword)
	if err != nil {
		logger.Error("password hashing failed", "error", err)
		os.Exit(1)
	}
	adminID, err := repository.CreateAdmin(ctx, *adminUsername, *adminDisplayName, "superadmin", adminHash)
	if err != nil {
		logger.Error("administrator bootstrap failed", "error", err)
		os.Exit(1)
	}
	logger.Info("administrator created", "id", adminID, "username", strings.ToLower(strings.TrimSpace(*adminUsername)))

	if *portalAccount != "" {
		portalHash, err := hasher.Hash(portalPassword)
		if err != nil {
			logger.Error("portal password hashing failed", "error", err)
			os.Exit(1)
		}
		portalID, err := repository.CreatePortalUser(ctx, *portalAccount, *portalName, portalHash)
		if err != nil {
			logger.Error("portal user bootstrap failed", "error", err)
			os.Exit(1)
		}
		logger.Info("portal user created", "id", portalID, "account", strings.ToLower(strings.TrimSpace(*portalAccount)))
	}
}

func env(key, fallback string) string {
	if value := strings.TrimSpace(os.Getenv(key)); value != "" {
		return value
	}
	return fallback
}
