package accntcli

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

	"mstore/app/accoper"
	"mstore/app/handler"
	"mstore/pkg/descr"
)

func (cli *Client) ListGrantsByUsername(ctx context.Context, host, username string) ([]descr.Grant, error) {
	var err error
	res := make([]descr.Grant, 0)
	params := accoper.ListGrantsParams{
		Username: username,
	}
	reqdata, err := json.Marshal(params)
	if err != nil {
		return res, err
	}
	respdata, err := cli.doHTTPCall(ctx, host, "grants", "list", reqdata)
	if err != nil {
		return res, err
	}

	response := handler.NewResponse[accoper.ListGrantsResult]()
	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.Grants
	return res, err
}

func (cli *Client) ListGrantsByAccountID(ctx context.Context, host, accountID string) ([]descr.Grant, error) {
	var err error
	res := make([]descr.Grant, 0)
	params := accoper.ListGrantsParams{
		AccountID: accountID,
	}
	reqdata, err := json.Marshal(params)
	if err != nil {
		return res, err
	}
	respdata, err := cli.doHTTPCall(ctx, host, "grants", "list", reqdata)
	if err != nil {
		return res, err
	}
	response := handler.NewResponse[accoper.ListGrantsResult]()
	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.Grants
	return res, err
}
