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

import (
	"context"
	"time"

	"github.com/spf13/cobra"

	"mstore/pkg/accntcli"
	"mstore/pkg/terms"
)

// CreateAccount
type CreateAccountParams struct {
	NewUsername string
	NewPassword string
}
type CreateAccountResult struct {
	AccountID string            `json:"accountId"`
	Grants    map[string]string `json:"grantsIds,omitempty"`
}

func (util *AccountUtil) CreateAccount(cmd *cobra.Command, args []string) {
	util.commonAccountParams.Hostname = args[0]
	util.createAccountParams.NewUsername = args[1]
	util.createAccountParams.NewPassword = args[2]
	res, err := util.createAccount(&util.commonAccountParams, &util.createAccountParams)
	printResponse(res, err)
}

func (util *AccountUtil) createAccount(common *CommonAccountParams, params *CreateAccountParams) (*CreateAccountResult, error) {
	var err error
	res := &CreateAccountResult{
		Grants: make(map[string]string, 0),
	}

	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)

	accountID, err := cli.CreateAccount(ctx, ref.Host(), params.NewUsername, params.NewPassword)
	if err != nil {
		return res, err
	}

	fullRights := []string{
		terms.RightWriteAccounts,
		terms.RightReadAccounts,
		terms.RightWriteFiles,
		terms.RightReadFiles,
		terms.RightWriteImages,
		terms.RightReadImages,
	}
	for _, right := range fullRights {
		id, err := cli.CreateGrantByAccountID(ctx, ref.Host(), accountID, right, ".*")
		if err != nil {
			return res, err
		}
		res.Grants[id] = right
	}
	res.AccountID = accountID
	return res, err
}
