package main

import (
	"flag"
	"fmt"
	"os"

	"party.at/party/cmd/party/common"
	"party.at/party/internal/data"
)

func runCreateAdmin(args []string) {
	fs := flag.NewFlagSet("create-admin", flag.ExitOnError)
	email := fs.String("email", "", "Admin email (required)")
	password := fs.String("password", "", "Admin password (required)")
	name := fs.String("name", "", "Admin name (required)")
	fs.Parse(args)

	if *email == "" || *password == "" || *name == "" {
		fmt.Fprintln(os.Stderr, "usage: party create-admin -email EMAIL -password PASSWORD -name NAME")
		os.Exit(1)
	}

	var cfg common.Config
	cfg.DB.DSN = os.Getenv("PARTY_DB_DSN")
	cfg.DB.MaxOpenConns = 5
	cfg.DB.MaxIdleConns = 5
	cfg.DB.MaxIdleTime = "15m"

	db, err := openDB(cfg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "db: %v\n", err)
		os.Exit(1)
	}
	defer db.Close()

	models := data.NewModels(db)

	user := &data.User{
		Email:     *email,
		Name:      *name,
		Activated: true,
	}

	userIdentity := &data.UserIdentity{
		ProviderID:     int64(data.ProviderLocal),
		ProviderUserID: *email,
	}
	if err := userIdentity.Password.Set(*password); err != nil {
		fmt.Fprintf(os.Stderr, "password: %v\n", err)
		os.Exit(1)
	}

	if err := models.Users.ExecuteRegistrationTx(user, userIdentity); err != nil {
		fmt.Fprintf(os.Stderr, "create user: %v\n", err)
		os.Exit(1)
	}

	if err := models.Roles.AssignToUser(user.ID, data.RoleAdmin); err != nil {
		fmt.Fprintf(os.Stderr, "assign role: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("created admin: id=%d email=%s\n", user.ID, user.Email)
}
