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

import (
	"context"
	"strings"
	"time"

	"github.com/spf13/cobra"

	"mstore/pkg/accntcli"
)

// UpdateGrant
type UpdateGrantParams struct {
	GrantID string
	Pattern string
}
type UpdateGrantResult struct{}

func (util *GrantUtil) UpdateGrant(cmd *cobra.Command, args []string) {
	util.commonGrantParams.Hostname = args[0]
	util.updateGrantParams.GrantID = args[1]
	util.updateGrantParams.Pattern = args[2]
	res, err := util.updateGrant(&util.commonGrantParams, &util.updateGrantParams)
	printResponse(res, err)
}

func (util *GrantUtil) updateGrant(common *CommonGrantParams, params *UpdateGrantParams) (*UpdateGrantResult, error) {
	var err error
	res := &UpdateGrantResult{}

	timeout := time.Duration(common.Timeout) * time.Second
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	ref, err := accntcli.ParseHostinfo(common.Hostname)
	if err != nil {
		return res, err
	}
	ref.SetUserinfo(common.Username, common.Password)
	mw := accntcli.NewBasicAuthMiddleware(ref.Userinfo())
	cli := accntcli.NewClient(nil, mw)

	id := strings.ToLower(params.GrantID)
	err = cli.UpdateGrant(ctx, ref.Host(), id, params.Pattern)
	if err != nil {
		return res, err
	}
	return res, err
}
