package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"strings"
	"time"

	"haixun-backend/internal/bootstrap"
	"haixun-backend/internal/config"

	"github.com/zeromicro/go-zero/core/conf"
)

func main() {
	if len(os.Args) < 2 {
		printUsage()
		os.Exit(1)
	}
	switch os.Args[1] {
	case "init":
		if err := runInit(os.Args[2:]); err != nil {
			fmt.Fprintf(os.Stderr, "[tool] error: %v\n", err)
			os.Exit(1)
		}
	default:
		fmt.Fprintf(os.Stderr, "[tool] unknown command: %s\n", os.Args[1])
		printUsage()
		os.Exit(1)
	}
}

func runInit(args []string) error {
	fs := flag.NewFlagSet("init", flag.ExitOnError)
	configFile := fs.String("f", "etc/gateway.yaml", "config file")
	tenantID := fs.String("tenant", envOr("INIT_TENANT_ID", "default"), "tenant id for admin and role permissions")
	email := fs.String("email", envOr("INIT_ADMIN_EMAIL", "admin@haixun.local"), "bootstrap admin email")
	password := fs.String("password", envOr("INIT_ADMIN_PASSWORD", "Admin-Pass-1!"), "bootstrap admin password")
	displayName := fs.String("display-name", envOr("INIT_ADMIN_DISPLAY_NAME", "Admin"), "bootstrap admin display name")
	if err := fs.Parse(args); err != nil {
		return err
	}

	var cfg config.Config
	conf.MustLoad(*configFile, &cfg)

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	report, err := bootstrap.Init(ctx, cfg, bootstrap.InitOptions{
		TenantID:    strings.TrimSpace(*tenantID),
		AdminEmail:  strings.TrimSpace(*email),
		AdminPass:   *password,
		DisplayName: strings.TrimSpace(*displayName),
	})
	if err != nil {
		return err
	}

	fmt.Fprintf(os.Stderr, "[tool] indexes ensured\n")
	fmt.Fprintf(os.Stderr, "[tool] permissions catalog seeded\n")
	fmt.Fprintf(os.Stderr, "[tool] role_permissions seeded (admin=all, user=default)\n")
	if report.AdminCreated {
		fmt.Fprintf(os.Stderr, "[tool] admin created uid=%s email=%s tenant=%s\n", report.AdminUID, *email, *tenantID)
	} else {
		fmt.Fprintf(os.Stderr, "[tool] admin exists uid=%s email=%s tenant=%s (roles ensured admin)\n", report.AdminUID, *email, *tenantID)
	}
	fmt.Printf("export INIT_TENANT_ID=%s\n", *tenantID)
	fmt.Printf("export INIT_ADMIN_EMAIL=%s\n", *email)
	fmt.Printf("export INIT_ADMIN_PASSWORD=%s\n", *password)
	fmt.Printf("export INIT_ADMIN_UID=%s\n", report.AdminUID)
	return nil
}

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

func printUsage() {
	fmt.Fprintf(os.Stderr, "usage:\n")
	fmt.Fprintf(os.Stderr, "  tool init [-f etc/gateway.yaml] [-tenant default] [-email admin@haixun.local] [-password ...]\n")
}
