/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package accountcmd

import (
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

type GrantUtil struct {
	createGrantParams CreateGrantParams
	updateGrantParams UpdateGrantParams
	getGrantParams    GetGrantParams
	deleteGrantParams DeleteGrantParams
	listGrantsParams  ListGrantsParams
	commonGrantParams CommonGrantParams
}

func NewGrantUtil() *GrantUtil {
	return &GrantUtil{}
}

func (util *GrantUtil) MakeGrantCmds() *cobra.Command {
	var subCmd = &cobra.Command{
		Use:     "grants",
		Short:   "Grant operations",
		Aliases: []string{"grant"},
	}
	const defaultTimeout uint64 = 10

	subCmd.PersistentFlags().StringVarP(&util.commonGrantParams.Username, "user", "u", "", "Username")
	subCmd.PersistentFlags().StringVarP(&util.commonGrantParams.Password, "pass", "p", "", "Password")
	subCmd.PersistentFlags().Uint64VarP(&util.commonGrantParams.Timeout, "timeout", "t", defaultTimeout, "Operation timeout")
	subCmd.PersistentFlags().BoolVarP(&util.commonGrantParams.SkipTLSVerify, "skipVerify", "S", true, "Skip server certificate verify")

	vi := viper.New()
	vi.SetEnvPrefix("mstore")
	vi.BindEnv("user")
	vi.BindEnv("pass")
	util.commonGrantParams.Username = vi.GetString("user")
	util.commonGrantParams.Password = vi.GetString("pass")

	// CreateGrant
	var createGrantCmd = &cobra.Command{
		Use:   "create [user:pass@]hostname[:port] username|accountId rigth pattern",
		Short: "Create grant",
		Args:  cobra.ExactArgs(4),
		Run:   util.CreateGrant,
	}
	subCmd.AddCommand(createGrantCmd)

	// GetGrant
	var getGrantCmd = &cobra.Command{
		Use:   "get [user:pass@]hostname[:port] grantId",
		Short: "Get detail grant info",
		Args:  cobra.ExactArgs(2),
		Run:   util.GetGrant,
	}
	subCmd.AddCommand(getGrantCmd)

	// UpdateGrant
	var updateGrantCmd = &cobra.Command{
		Use:   "update [user:pass@]hostname[:port] gruntId newPattern",
		Short: "Update grant parameters",
		Args:  cobra.ExactArgs(3),
		Run:   util.UpdateGrant,
	}
	subCmd.AddCommand(updateGrantCmd)

	// DeleteGrant
	var deleteGrantCmd = &cobra.Command{
		Use:   "delete [user:pass@]hostname[:port] gruntId ",
		Short: "Delete grant",
		Args:  cobra.ExactArgs(2),

		Run: util.DeleteGrant,
	}
	subCmd.AddCommand(deleteGrantCmd)

	// ListGrants
	var listGrantsCmd = &cobra.Command{
		Use:   "list [user:pass@]hostname[:port] accountId|username",
		Short: "list user grants",
		Args:  cobra.ExactArgs(2),
		Run:   util.ListGrants,
	}
	listGrantsCmd.Flags().BoolVarP(&util.listGrantsParams.Detail, "detail", "d", false, "Show detail information")

	subCmd.AddCommand(listGrantsCmd)

	return subCmd
}

type CommonGrantParams struct {
	Username      string
	Password      string
	Hostname      string
	Timeout       uint64
	SkipTLSVerify bool
}
