package accntcli

import (
	"context"
	"encoding/json"
	"errors"

	"mstore/app/accoper"
	"mstore/app/handler"
)

func (cli *Client) CreateGrantByAccountID(ctx context.Context, host string, accountID, right, pattern string) (string, error) {
	var err error
	var res string

	params := accoper.CreateGrantParams{
		AccountID: accountID,
		Right:     right,
		Pattern:   pattern,
	}
	reqdata, err := json.Marshal(params)
	if err != nil {
		return res, err
	}
	respdata, err := cli.doHTTPCall(ctx, host, "grant", "create", reqdata)
	if err != nil {
		return res, err
	}

	response := handler.NewResponse[accoper.CreateGrantResult]()
	err = json.Unmarshal(respdata, response)
	if err != nil {
		return res, err
	}
	if response.Error {
		err = errors.New(response.Message)
		return res, err
	}
	res = response.Result.GrantID
	return res, err
}

func (cli *Client) CreateGrantByUsername(ctx context.Context, host, username string, right string, pattern string) (string, error) {
	var err error
	var res string
	params := accoper.CreateGrantParams{
		Username: username,
		Right:    right,
		Pattern:  pattern,
	}
	reqdata, err := json.Marshal(params)
	if err != nil {
		return res, err
	}
	respdata, err := cli.doHTTPCall(ctx, host, "grant", "create", reqdata)
	if err != nil {
		return res, err
	}

	response := handler.NewResponse[accoper.CreateGrantResult]()
	err = json.Unmarshal(respdata, response)
	if err != nil {
		return res, err
	}
	if response.Error {
		err = errors.New(response.Message)
		return res, err
	}
	res = response.Result.GrantID
	return res, err
}
