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

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

	"github.com/spf13/cobra"

	"mstore/pkg/accntcli"
)

// DeleteAccount
type DeleteAccountParams struct {
	AccountID string
	Timeout   uint64
}

type DeleteAccountResult struct{}

func (util *AccountUtil) DeleteAccount(cmd *cobra.Command, args []string) {
	util.commonAccountParams.Hostname = args[0]
	util.deleteAccountParams.AccountID = args[1]
	res, err := util.deleteAccount(&util.commonAccountParams, &util.deleteAccountParams)
	printResponse(res, err)
}
func (util *AccountUtil) deleteAccount(common *CommonAccountParams, params *DeleteAccountParams) (*DeleteAccountResult, error) {
	var err error
	res := &DeleteAccountResult{}

	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)

	re := regexp.MustCompile(uuidRegex)
	id := strings.ToLower(params.AccountID)
	if re.MatchString(id) {
		err = cli.DeleteAccountByID(ctx, ref.Host(), id)
	} else {
		err = cli.DeleteAccountByName(ctx, ref.Host(), params.AccountID)
	}
	if err != nil {
		return res, err
	}
	return res, err
}
