/*
 * 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"
	"time"

	"github.com/spf13/cobra"

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

// ListAccounts
type ListAccountsParams struct {
	Timeout uint64
	Detail  bool
	Regex   string
}

type Userinfo struct {
	Username  string            `json:"username,omitempty"`
	AccountID string            `json:"accountId,omitempty"`
	Rights    map[string]string `json:"rights,omitempty"`
}

type ListAccountsResult struct {
	Accounts []descr.AccountShort `json:"accounts,omitempty"`
	Users    []Userinfo           `json:"users,omitempty"`
}

func (util *AccountUtil) ListAccounts(cmd *cobra.Command, args []string) {
	util.commonAccountParams.Hostname = args[0]
	res, err := util.listAccounts(&util.commonAccountParams, &util.listAccountsParams)
	printResponse(res, err)
}
func (util *AccountUtil) listAccounts(common *CommonAccountParams, params *ListAccountsParams) (*ListAccountsResult, error) {
	var err error
	res := &ListAccountsResult{}

	outregex, err := regexp.Compile(params.Regex)
	if err != nil {
		return res, err
	}

	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)

	accounts, err := cli.ListAccounts(ctx, ref.Host())
	if err != nil {
		return res, err
	}
	outAccounts := make([]descr.AccountShort, 0)
	if params.Regex != "" {
		for _, item := range accounts {
			if outregex.MatchString(item.Username) {
				outAccounts = append(outAccounts, item)
			}
		}
	} else {
		outAccounts = accounts
	}
	if params.Detail {
		res.Accounts = outAccounts
	} else {
		res.Users = make([]Userinfo, 0)
		for _, account := range outAccounts {
			userinfo := Userinfo{
				Username:  account.Username,
				AccountID: account.ID,
				Rights:    make(map[string]string, 0),
			}
			for _, grant := range account.Grants {
				userinfo.Rights[grant.ID] = grant.Right
			}
			res.Users = append(res.Users, userinfo)
		}
	}
	return res, err
}
