package accoper

import (
	"context"
	"fmt"

	"mstore/pkg/auxtool"
	"mstore/pkg/descr"
)

// UpdateGrant
type UpdateGrantParams struct {
	GrantID    string
	NewPattern string
}
type UpdateGrantResult struct{}

func (oper *Operator) UpdateGrant(ctx context.Context, operatorID string, params *UpdateGrantParams) (*UpdateGrantResult, error) {
	var err error
	res := &UpdateGrantResult{}

	if params.NewPattern == "" {
		err := fmt.Errorf("Empty newPattern parameter")
		return res, err
	}
	if params.GrantID == "" {
		err := fmt.Errorf("Empty grantId parameter")
		return res, err
	}
	var grantDescr *descr.Grant
	var grantExists bool

	grantExists, grantDescr, err = oper.mdb.GetGrantByID(ctx, params.GrantID)
	if err != nil {
		return res, err
	}
	if !grantExists {
		err := fmt.Errorf("Grant with ID %s dont exists", params.GrantID)
		return res, err
	}
	now := auxtool.TimeNow()
	if params.NewPattern != "" {
		grantDescr.UpdatedAt = now
		grantDescr.UpdatedBy = operatorID
		grantDescr.Pattern = params.NewPattern
	}
	err = oper.mdb.UpdateGrantByID(ctx, grantDescr.ID, grantDescr)
	if err != nil {
		return res, err
	}
	return res, err
}
