package operator

import (
	"context"
	"fmt"

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

type CreateAccountParams struct {
	Username string `json:"username"`
	Password string `json:"password"`
}
type CreateAccountResult struct {
	AccountID string `json:"accountId"`
}

func (oper *Operator) CreateAccount(ctx context.Context, operatorID string, params *CreateAccountParams) (*CreateAccountResult, error) {
	var err error
	res := &CreateAccountResult{}

	if params.Username == "" {
		err := fmt.Errorf("Empty username parameters")
		return res, err
	}

	if params.Password == "" {
		err := fmt.Errorf("Empty password parameter")
		return res, err
	}

	accountExists, _, err := oper.mdb.GetAccountByUsername(ctx, params.Username)
	if err != nil {
		return res, err
	}
	if accountExists {
		err := fmt.Errorf("Account with thist name already exists")
		return res, err
	}
	now := auxtool.TimeNow()
	passhash := auxpwd.MakeSHA256Hash([]byte(params.Password))
	accountDescr := &descr.Account{
		ID:        auxuuid.NewUUID(),
		Username:  params.Username,
		Passhash:  passhash,
		Disabled:  false,
		CreatedAt: now,
		UpdatedAt: now,
		CreatedBy: operatorID,
		UpdatedBy: operatorID,
	}
	err = oper.mdb.InsertAccount(ctx, accountDescr)
	if err != nil {
		return res, err
	}
	res.AccountID = accountDescr.ID
	return res, err
}

// GetAccount
type GetAccountParams struct {
	Username  string `json:"username"`
	AccountID string `json:"accountId"`
}
type GetAccountResult struct {
	Account *descr.AccountShort `json:"account"`
}

func (oper *Operator) GetAccount(ctx context.Context, operatorID string, params *GetAccountParams) (*GetAccountResult, error) {
	var err error
	res := &GetAccountResult{}

	if params.Username == "" && params.AccountID == "" {
		err := fmt.Errorf("Empty username and accountId parameter")
		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
	}
	if accountDescr == nil {
		err := fmt.Errorf("Null account desriptor")
		return res, err
	}
	accountShort := &descr.AccountShort{
		ID:        accountDescr.ID,
		Username:  accountDescr.Username,
		CreatedAt: accountDescr.CreatedAt,
		UpdatedAt: accountDescr.UpdatedAt,
		CreatedBy: accountDescr.CreatedBy,
		UpdatedBy: accountDescr.UpdatedBy,
		Disabled:  accountDescr.Disabled,
		Grants:    make([]descr.Grant, 0),
	}
	grantDescrs, err := oper.mdb.ListGrantsByAccountID(ctx, accountDescr.ID)
	if err != nil {
		return res, err
	}
	accountShort.Grants = grantDescrs

	res.Account = accountShort
	return res, err
}

type UpdateAccountParams struct {
	Username    string `json:"username"`
	AccountID   string `json:"accountId"`
	NewUsername string `json:"newUsername"`
	NewPassword string `json:"newPassword"`
	Disabled    bool   `json:"disabled"`
}
type UpdateAccountResult struct{}

func (oper *Operator) UpdateAccount(ctx context.Context, operatorID string, params *UpdateAccountParams) (*UpdateAccountResult, error) {
	var err error
	res := &UpdateAccountResult{}
	if params.Username == "" && params.AccountID == "" {
		err := fmt.Errorf("Empty username and accountId parameter")
		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
	}
	if accountDescr == nil {
		err := fmt.Errorf("Null account desriptor")
		return res, err
	}
	now := auxtool.TimeNow()
	if params.NewUsername != "" {
		accountDescr.UpdatedAt = now
		accountDescr.Username = params.NewUsername
	}
	if params.NewPassword != "" {
		accountDescr.UpdatedAt = now
		passhash := auxpwd.MakeSHA256Hash([]byte(params.NewPassword))
		accountDescr.Passhash = passhash
	}
	if params.Disabled != accountDescr.Disabled {
		accountDescr.UpdatedAt = now
		accountDescr.Disabled = params.Disabled
	}

	err = oper.mdb.UpdateAccountByID(ctx, accountDescr.ID, accountDescr)
	if err != nil {
		return res, err
	}
	return res, err
}

type DeleteAccountParams struct {
	Username  string `json:"username"`
	AccountID string `json:"accountId"`
}
type DeleteAccountResult struct{}

func (oper *Operator) DeleteAccount(ctx context.Context, operatorID string, params *DeleteAccountParams) (*DeleteAccountResult, error) {
	var err error
	res := &DeleteAccountResult{}

	if params.Username == "" && params.AccountID == "" {
		err := fmt.Errorf("Empty username and accountId parameter")
		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
	}
	if accountDescr == nil {
		err := fmt.Errorf("Null account desriptor")
		return res, err
	}
	err = oper.mdb.DeleteAllGrantsForAccountID(ctx, accountDescr.ID)
	if err != nil {
		return res, err
	}
	err = oper.mdb.DeleteAccountByID(ctx, accountDescr.ID)
	if err != nil {
		return res, err
	}
	return res, err
}

type ListAccountsParams struct{}
type ListAccountsResult struct {
	Accounts []descr.AccountShort `json:"accounts"`
}

func (oper *Operator) ListAccounts(ctx context.Context, params *ListAccountsParams) (*ListAccountsResult, error) {
	var err error
	res := &ListAccountsResult{
		Accounts: make([]descr.AccountShort, 0),
	}

	accountDescrs, err := oper.mdb.ReducedListAccounts(ctx)
	if err != nil {
		return res, err
	}
	for _, accountDescr := range accountDescrs {
		accountShort := descr.AccountShort{
			ID:        accountDescr.ID,
			Username:  accountDescr.Username,
			Disabled:  accountDescr.Disabled,
			CreatedAt: accountDescr.CreatedAt,
			UpdatedAt: accountDescr.UpdatedAt,
			CreatedBy: accountDescr.CreatedBy,
			UpdatedBy: accountDescr.UpdatedBy,
			Grants:    make([]descr.Grant, 0),
		}
		grantDescrs, err := oper.mdb.ListGrantsByAccountID(ctx, accountDescr.ID)
		if err != nil {
			return res, err
		}
		accountShort.Grants = grantDescrs
		res.Accounts = append(res.Accounts, accountShort)
	}
	return res, err
}
