package paymentapiimp

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/mutil/mzap"
	tracev1 "github.com/tech/sendico/pkg/proto/common/trace/v1"
	orchestrationv2 "github.com/tech/sendico/pkg/proto/payments/orchestration/v2"
	quotationv2 "github.com/tech/sendico/pkg/proto/payments/quotation/v2"
	sharedv1 "github.com/tech/sendico/pkg/proto/payments/shared/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/v2/bson"
	"go.uber.org/zap"
)

// shared initiation pipeline
func (a *PaymentAPI) initiatePayment(r *http.Request, account *model.Account, token *sresponse.TokenData, expectQuote bool) http.HandlerFunc {
	orgRef, err := a.oph.GetRef(r)
	if err != nil {
		a.logger.Warn("Failed to parse organization reference for payment initiation", zap.Error(err), mutil.PLog(a.oph, 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, bson.NilObjectID, model.ActionCreate)
	if err != nil {
		a.logger.Warn("Failed to check payments 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 initiating payment", mutil.PLog(a.oph, r))
		return response.AccessDenied(a.logger, a.Name(), "payments write permission denied")
	}

	payload, err := decodeInitiatePayload(r)
	if err != nil {
		return response.BadPayload(a.logger, a.Name(), err)
	}

	if expectQuote {
		if payload.QuoteRef == "" {
			return response.BadPayload(a.logger, a.Name(), merrors.InvalidArgument("quoteRef is required"))
		}
		if payload.Intent != nil {
			return response.BadPayload(a.logger, a.Name(), merrors.DataConflict("quoteRef cannot be combined with intent"))
		}
	} else {
		if payload.Intent == nil {
			return response.BadPayload(a.logger, a.Name(), merrors.InvalidArgument("intent is required"))
		}
		if payload.QuoteRef != "" {
			return response.BadPayload(a.logger, a.Name(), merrors.DataConflict("quoteRef cannot be used when intent is provided"))
		}
	}

	quotationRef := strings.TrimSpace(payload.QuoteRef)
	if metadataValue(payload.Metadata, "intent_ref") != "" {
		return response.BadPayload(a.logger, a.Name(), merrors.InvalidArgument("metadata.intent_ref is no longer supported", "metadata.intent_ref"))
	}
	if payload.Intent != nil {
		applyCustomerIP(payload.Intent, r.RemoteAddr)
		intent, err := mapQuoteIntent(payload.Intent)
		if err != nil {
			return response.BadPayload(a.logger, a.Name(), err)
		}
		quoteResp, qErr := a.quotation.QuotePayment(ctx, &quotationv2.QuotePaymentRequest{
			Meta:           requestMeta(orgRef.Hex(), payload.IdempotencyKey),
			IdempotencyKey: strings.TrimSpace(payload.IdempotencyKey),
			Intent:         intent,
			InitiatorRef:   initiatorRef(account),
		})
		if qErr != nil {
			a.logger.Warn("Failed to quote payment before execution", zap.Error(qErr), mzap.ObjRef("organization_ref", orgRef))
			return grpcErrorResponse(a.logger, a.Name(), qErr)
		}
		quotationRef = strings.TrimSpace(quoteResp.GetQuote().GetQuoteRef())
		if quotationRef == "" {
			return response.Auto(a.logger, a.Name(), merrors.DataConflict("quotation service returned empty quote_ref"))
		}
	}

	req := &orchestrationv2.ExecutePaymentRequest{
		Meta:             requestMeta(orgRef.Hex(), payload.IdempotencyKey),
		QuotationRef:     quotationRef,
		ClientPaymentRef: strings.TrimSpace(payload.ClientPaymentRef),
	}

	resp, err := a.execution.ExecutePayment(ctx, req)
	if err != nil {
		a.logger.Warn("Failed to initiate payment", zap.Error(err), mzap.ObjRef("organization_ref", orgRef))
		return grpcErrorResponse(a.logger, a.Name(), err)
	}

	return sresponse.PaymentResponse(a.logger, resp.GetPayment(), token)
}

func decodeInitiatePayload(r *http.Request) (*srequest.InitiatePayment, error) {
	defer func() {
		_ = r.Body.Close()
	}()

	payload := &srequest.InitiatePayment{}
	if err := json.NewDecoder(r.Body).Decode(payload); err != nil {
		return nil, merrors.InvalidArgument("invalid payload: " + err.Error())
	}
	payload.IdempotencyKey = strings.TrimSpace(payload.IdempotencyKey)
	payload.QuoteRef = strings.TrimSpace(payload.QuoteRef)
	payload.ClientPaymentRef = strings.TrimSpace(payload.ClientPaymentRef)

	if err := payload.Validate(); err != nil {
		return nil, err
	}
	return payload, nil
}

func requestMeta(organizationRef string, idempotencyKey string) *sharedv1.RequestMeta {
	return &sharedv1.RequestMeta{
		OrganizationRef: strings.TrimSpace(organizationRef),
		Trace: &tracev1.TraceContext{
			IdempotencyKey: strings.TrimSpace(idempotencyKey),
		},
	}
}

func metadataValue(meta map[string]string, key string) string {
	if len(meta) == 0 {
		return ""
	}
	return strings.TrimSpace(meta[strings.TrimSpace(key)])
}

func initiatorRef(account *model.Account) string {
	if account == nil {
		return ""
	}
	if account.ID != bson.NilObjectID {
		return account.ID.Hex()
	}
	return strings.TrimSpace(account.Login)
}
