package accoper

import (
	"context"
	"fmt"
	"regexp"

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

// CreateGrant
type CreateGrantParams struct {
	AccountID string `json:"accountID"`
	Username  string `json:"username"`
	Right     string `json:"operation"`
	Pattern   string `json:"pattern"`
}
type CreateGrantResult struct {
	GrantID string `json:"grantId"`
}

func (oper *Operator) CreateGrant(ctx context.Context, operatorID string, params *CreateGrantParams) (*CreateGrantResult, error) {
	var err error
	res := &CreateGrantResult{}

	if params.AccountID == "" {
		err := fmt.Errorf("Empty accountId parameters")
		return res, err
	}
	if params.Right == "" {
		err := fmt.Errorf("Empty operation parameter")
		return res, err
	}
	if params.Pattern == "" {
		err := fmt.Errorf("Empty pattern parameter")
		return res, err
	}

	_, err = regexp.Compile(params.Pattern)
	if err != nil {
		err := fmt.Errorf("Cannot compile regexp %s: %v", err)
		return res, err
	}

	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
	}
	grantExists, _, err := oper.mdb.GetGrantByAccoundIDRightPattern(ctx, params.AccountID, params.Right, params.Pattern)
	if err != nil {
		return res, err
	}
	if grantExists {
		err := fmt.Errorf("Grant with this right already exists")
		return res, err
	}
	now := auxtool.TimeNow()
	grantDescr := &descr.Grant{
		ID:        auxuuid.NewUUID(),
		AccountID: accountDescr.ID,
		Right:     params.Right,
		Pattern:   params.Pattern,
		CreatedAt: now,
		UpdatedAt: now,
		CreatedBy: operatorID,
		UpdatedBy: operatorID,
	}
	err = oper.mdb.InsertGrant(ctx, grantDescr)
	if err != nil {
		return res, err
	}
	res.GrantID = grantDescr.ID
	return res, err
}
