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

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

	"github.com/spf13/cobra"

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

// GetAccount
type GetAccountParams struct {
	Timeout   uint64
	AccountID string
}

func (util *AccountUtil) GetAccount(cmd *cobra.Command, args []string) {
	util.commonAccountParams.Hostname = args[0]
	util.getAccountParams.AccountID = args[1]
	res, err := util.getAccount(&util.commonAccountParams, &util.getAccountParams)
	printResponse(res, err)
}

type GetAccountResult struct {
	Account *descr.AccountShort `json:"account,omitempty"`
}

func (util *AccountUtil) getAccount(common *CommonAccountParams, params *GetAccountParams) (*GetAccountResult, error) {
	var err error
	res := &GetAccountResult{}
	opres := &descr.AccountShort{}
	re := regexp.MustCompile(uuidRegex)
	id := strings.ToLower(params.AccountID)

	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)
	if re.MatchString(id) {
		opres, err = cli.GetAccountByID(ctx, ref.Host(), id)
	} else {
		opres, err = cli.GetAccountByName(ctx, ref.Host(), params.AccountID)
	}
	if err != nil {
		return res, err
	}
	res.Account = opres
	return res, err
}
