package accoper

import (
	"context"
	"fmt"

	"mstore/pkg/descr"
)

// ListGrants
type ListGrantsParams struct {
	Username  string
	AccountID string
}
type ListGrantsResult struct {
	Grants []descr.Grant `json:"grants"`
}

func (oper *Operator) ListGrants(ctx context.Context, operatorID string, params *ListGrantsParams) (*ListGrantsResult, error) {
	var err error
	res := &ListGrantsResult{
		Grants: make([]descr.Grant, 0),
	}
	var accountDescr *descr.Account
	var accountExists bool
	switch {
	case params.AccountID != "":
		accountExists, accountDescr, err = oper.mdb.GetAccountByID(ctx, params.AccountID)
		if err != nil {
			return res, err
		}
		if !accountExists {
			err := fmt.Errorf("Account with ID %s dont exists", params.AccountID)
			return res, err
		}
	case params.Username != "":
		accountExists, accountDescr, err = oper.mdb.GetAccountByUsername(ctx, params.Username)
		if err != nil {
			return res, err
		}
		if !accountExists {
			err := fmt.Errorf("Account with name %s dont exists", params.Username)
			return res, err
		}
	default:
		err := fmt.Errorf("Empty username and accountId parameter")
		return res, err
	}
	accountID := accountDescr.ID
	grantDescrs, err := oper.mdb.ListGrantsByAccountID(ctx, accountID)
	if err != nil {
		return res, err
	}
	res.Grants = grantDescrs
	return res, err
}
