package ledgerapiimp

import (
	"encoding/json"
	"net/http"
	"strings"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	describablev1 "github.com/tech/sendico/pkg/proto/common/describable/v1"
	ledgerv1 "github.com/tech/sendico/pkg/proto/ledger/v1"
	"github.com/tech/sendico/server/interface/api/srequest"
	"github.com/tech/sendico/server/interface/api/sresponse"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.uber.org/zap"
)

func (a *LedgerAPI) createAccount(r *http.Request, account *model.Account, token *sresponse.TokenData) http.HandlerFunc {
	orgRef, err := a.oph.GetRef(r)
	if err != nil {
		a.logger.Warn("Failed to parse organization reference for ledger account create", zap.Error(err), zap.String(a.oph.Name(), a.oph.GetID(r)))
		return response.BadReference(a.logger, a.Name(), a.oph.Name(), a.oph.GetID(r), err)
	}

	ctx := r.Context()
	allowed, err := a.enf.Enforce(ctx, a.permissionRef, account.ID, orgRef, primitive.NilObjectID, model.ActionCreate)
	if err != nil {
		a.logger.Warn("Failed to check ledger accounts access permissions", zap.Error(err), mutil.PLog(a.oph, r))
		return response.Auto(a.logger, a.Name(), err)
	}
	if !allowed {
		a.logger.Debug("Access denied when creating ledger account", mutil.PLog(a.oph, r))
		return response.AccessDenied(a.logger, a.Name(), "ledger accounts write permission denied")
	}

	payload, err := decodeLedgerAccountCreatePayload(r)
	if err != nil {
		a.logger.Warn("Failed to decode ledger account create payload", zap.Error(err), mutil.PLog(a.oph, r))
		return response.BadPayload(a.logger, a.Name(), err)
	}

	accountType, err := mapLedgerAccountType(payload.AccountType)
	if err != nil {
		return response.BadPayload(a.logger, a.Name(), err)
	}
	status, err := mapLedgerAccountStatus(payload.Status)
	if err != nil {
		return response.BadPayload(a.logger, a.Name(), err)
	}

	if a.client == nil {
		return response.Internal(a.logger, mservice.Ledger, merrors.Internal("ledger client is not configured"))
	}

	var describable *describablev1.Describable
	name := strings.TrimSpace(payload.Describable.Name)
	var description *string
	if payload.Describable.Description != nil {
		trimmed := strings.TrimSpace(*payload.Describable.Description)
		if trimmed != "" {
			description = &trimmed
		}
	}
	if name != "" || description != nil {
		describable = &describablev1.Describable{
			Name:        name,
			Description: description,
		}
	}
	var ownerRef string
	if !payload.IsOrgWallet {
		ownerRef = account.ID.Hex()
	}

	resp, err := a.client.CreateAccount(ctx, &ledgerv1.CreateAccountRequest{
		OrganizationRef: orgRef.Hex(),
		OwnerRef:        ownerRef,
		AccountCode:     payload.AccountCode,
		AccountType:     accountType,
		Currency:        payload.Currency,
		Status:          status,
		AllowNegative:   payload.AllowNegative,
		IsSettlement:    payload.IsSettlement,
		Metadata:        payload.Metadata,
		Describable:     describable,
	})
	if err != nil {
		a.logger.Warn("Failed to create ledger account", zap.Error(err), zap.String("organization_ref", orgRef.Hex()))
		return response.Auto(a.logger, mservice.Ledger, err)
	}

	return sresponse.LedgerAccountCreated(a.logger, resp.GetAccount(), token)
}

func decodeLedgerAccountCreatePayload(r *http.Request) (*srequest.CreateLedgerAccount, error) {
	defer r.Body.Close()

	payload := srequest.CreateLedgerAccount{}
	if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
		return nil, merrors.InvalidArgument("invalid payload: " + err.Error())
	}
	payload.AccountCode = strings.TrimSpace(payload.AccountCode)
	payload.Currency = strings.ToUpper(strings.TrimSpace(payload.Currency))
	payload.Describable.Name = strings.TrimSpace(payload.Describable.Name)
	if payload.Describable.Description != nil {
		trimmed := strings.TrimSpace(*payload.Describable.Description)
		if trimmed == "" {
			payload.Describable.Description = nil
		} else {
			payload.Describable.Description = &trimmed
		}
	}
	if len(payload.Metadata) == 0 {
		payload.Metadata = nil
	}
	if err := payload.Validate(); err != nil {
		return nil, err
	}
	return &payload, nil
}

func mapLedgerAccountType(accountType srequest.LedgerAccountType) (ledgerv1.AccountType, error) {
	switch strings.ToUpper(strings.TrimSpace(string(accountType))) {
	case "ACCOUNT_TYPE_ASSET", "ASSET":
		return ledgerv1.AccountType_ACCOUNT_TYPE_ASSET, nil
	case "ACCOUNT_TYPE_LIABILITY", "LIABILITY":
		return ledgerv1.AccountType_ACCOUNT_TYPE_LIABILITY, nil
	case "ACCOUNT_TYPE_REVENUE", "REVENUE":
		return ledgerv1.AccountType_ACCOUNT_TYPE_REVENUE, nil
	case "ACCOUNT_TYPE_EXPENSE", "EXPENSE":
		return ledgerv1.AccountType_ACCOUNT_TYPE_EXPENSE, nil
	case "", "ACCOUNT_TYPE_UNSPECIFIED", "UNSPECIFIED":
		return ledgerv1.AccountType_ACCOUNT_TYPE_UNSPECIFIED, merrors.InvalidArgument("accountType is required", "accountType")
	default:
		return ledgerv1.AccountType_ACCOUNT_TYPE_UNSPECIFIED, merrors.InvalidArgument("unsupported accountType: "+string(accountType), "accountType")
	}
}

func mapLedgerAccountStatus(status srequest.LedgerAccountStatus) (ledgerv1.AccountStatus, error) {
	switch strings.ToUpper(strings.TrimSpace(string(status))) {
	case "", "ACCOUNT_STATUS_UNSPECIFIED", "UNSPECIFIED":
		return ledgerv1.AccountStatus_ACCOUNT_STATUS_UNSPECIFIED, nil
	case "ACCOUNT_STATUS_ACTIVE", "ACTIVE":
		return ledgerv1.AccountStatus_ACCOUNT_STATUS_ACTIVE, nil
	case "ACCOUNT_STATUS_FROZEN", "FROZEN":
		return ledgerv1.AccountStatus_ACCOUNT_STATUS_FROZEN, nil
	default:
		return ledgerv1.AccountStatus_ACCOUNT_STATUS_UNSPECIFIED, merrors.InvalidArgument("unsupported status: "+string(status), "status")
	}
}
