package operator

import (
	"context"
	"fmt"
	"regexp"

	"mstore/pkg/auxtool"
	"mstore/pkg/descr"
	"mstore/pkg/term"
	"mstore/pkg/uuid"
)

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

func (oper *Operator) CreateGrant(ctx context.Context, operatorID uuid.UUID, 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
	}
	oper.logg.Debugf("Call CreateGrant")
	now := auxtool.TimeNow()
	grantDescr := &descr.Grant{
		ID:        uuid.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
}

// UpdateGrant
type UpdateGrantParams struct {
	GrantID    uuid.UUID
	NewPattern string
}
type UpdateGrantResult struct{}

func (oper *Operator) UpdateGrant(ctx context.Context, operatorID uuid.UUID, 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
}

// DeleteGrant
type DeleteGrantParams struct {
	GrantID uuid.UUID `json:"grantId"`
}
type DeleteGrantResult struct{}

func (oper *Operator) DeleteGrant(ctx context.Context, operatorID uuid.UUID, params *DeleteGrantParams) (*DeleteGrantResult, error) {
	var err error
	res := &DeleteGrantResult{}

	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
	}
	err = oper.mdb.DeleteGrantByID(ctx, grantDescr.ID)
	if err != nil {
		return res, err
	}
	return res, err
}

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

func (oper *Operator) ListGrants(ctx context.Context, operatorID uuid.UUID, 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
}

// Get Grants
type GetGrantParams struct {
	GrantID uuid.UUID `json:"grantId"`
}
type GetGrantResult struct {
	Grant *descr.Grant `json:"grant"`
}

func (oper *Operator) GetGrant(ctx context.Context, operatorID uuid.UUID, params *GetGrantParams) (*GetGrantResult, error) {
	var err error
	res := &GetGrantResult{}

	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
	}

	res.Grant = grantDescr
	return res, err
}
