/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 * This work is published and licensed under a Creative Commons
 * Attribution-NonCommercial-NoDerivatives 4.0 International License.
 *
 * Distribution of this work is permitted, but commercial use and
 * modifications are strictly prohibited.
 */
package accountcmd

import (
	"context"
	"regexp"
	"strings"
	"time"

	"github.com/spf13/cobra"

	"mstore/pkg/accntcli"
	"mstore/pkg/descr"
)

// ListGrants
type ListGrantsParams struct {
	Detail    bool
	AccountID string
}

type ListGrantsResult struct {
	Grants []descr.Grant     `json:"grants,omitempty"`
	Rights map[string]string `json:"rights,omitempty"`
}

func (util *GrantUtil) ListGrants(cmd *cobra.Command, args []string) {
	util.commonGrantParams.Hostname = args[0]
	util.listGrantsParams.AccountID = args[1]
	res, err := util.listGrants(&util.commonGrantParams, &util.listGrantsParams)
	printResponse(res, err)
}
func (util *GrantUtil) listGrants(common *CommonGrantParams, params *ListGrantsParams) (*ListGrantsResult, error) {
	var err error
	res := &ListGrantsResult{}

	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)

	grants := make([]descr.Grant, 0)
	re := regexp.MustCompile(uuidRegex)
	id := strings.ToLower(params.AccountID)
	if re.MatchString(id) {
		grants, err = cli.ListGrantsByAccountID(ctx, ref.Host(), id)
	} else {
		grants, err = cli.ListGrantsByUsername(ctx, ref.Host(), params.AccountID)
	}
	if err != nil {
		return res, err
	}
	if params.Detail {
		res.Grants = grants
	} else {
		res.Rights = make(map[string]string, 0)
		for _, item := range grants {
			res.Rights[item.ID] = item.Right
		}
	}
	return res, err
}
