package accntcli

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

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

func (cli *Client) UpdateAccountByName(ctx context.Context, host, username, newUsername, newPassword string) error {
	var err error
	params := accoper.UpdateAccountParams{
		Username:    username,
		NewUsername: newUsername,
		NewPassword: newPassword,
	}
	reqdata, err := json.Marshal(params)
	if err != nil {
		return err
	}
	resdata, err := cli.doHTTPCall(ctx, host, "account", "update", reqdata)
	if err != nil {
		return err
	}
	response := handler.NewResponse[accoper.UpdateAccountResult]()
	err = json.Unmarshal(resdata, response)
	if err != nil {
		return err
	}
	if response.Error {
		err = errors.New(response.Message)
		return err
	}
	return err
}

func (cli *Client) UpdateAccountByID(ctx context.Context, host string, accountID, newUsername, newPassword string) error {
	var err error
	params := accoper.UpdateAccountParams{
		AccountID:   accountID,
		NewUsername: newUsername,
		NewPassword: newPassword,
	}
	reqdata, err := json.Marshal(params)
	if err != nil {
		return err
	}
	resdata, err := cli.doHTTPCall(ctx, host, "account", "update", reqdata)
	if err != nil {
		return err
	}
	response := handler.NewResponse[accoper.UpdateAccountResult]()
	err = json.Unmarshal(resdata, response)
	if err != nil {
		return err
	}
	if response.Error {
		err = errors.New(response.Message)
		return err
	}
	return err
}
