package accntcli

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

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

func (cli *Client) GetAccountByName(ctx context.Context, host, username string) (*descr.AccountShort, error) {
	var err error
	res := &descr.AccountShort{}
	params := accoper.GetAccountParams{
		Username: username,
	}
	reqdata, err := json.Marshal(params)
	if err != nil {
		return res, err
	}
	resdata, err := cli.doHTTPCall(ctx, host, "account", "get", reqdata)
	if err != nil {
		return res, err
	}
	response := handler.NewResponse[accoper.GetAccountResult]()
	err = json.Unmarshal(resdata, response)
	if err != nil {
		return res, err
	}
	if response.Error {
		err = errors.New(response.Message)
		return res, err
	}
	res = response.Result.Account
	return res, err
}

func (cli *Client) GetAccountByID(ctx context.Context, host, accountID string) (*descr.AccountShort, error) {
	var err error
	res := &descr.AccountShort{}

	params := accoper.GetAccountParams{
		AccountID: accountID,
	}
	reqdata, err := json.Marshal(params)
	if err != nil {
		return res, err
	}
	resdata, err := cli.doHTTPCall(ctx, host, "account", "get", reqdata)
	if err != nil {
		return res, err
	}

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