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"
	orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/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"
)

// 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, primitive.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"))
		}
	}

	var intent *orchestratorv1.PaymentIntent
	if payload.Intent != nil {
		applyCustomerIP(payload.Intent, r.RemoteAddr)
		intent, err = mapPaymentIntent(payload.Intent)
		if err != nil {
			return response.BadPayload(a.logger, a.Name(), err)
		}
	}

	req := &orchestratorv1.InitiatePaymentRequest{
		Meta: &orchestratorv1.RequestMeta{
			OrganizationRef: orgRef.Hex(),
		},
		IdempotencyKey: strings.TrimSpace(payload.IdempotencyKey),
		Intent:         intent,
		QuoteRef:       strings.TrimSpace(payload.QuoteRef),
		Metadata:       payload.Metadata,
	}

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

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

func decodeInitiatePayload(r *http.Request) (*srequest.InitiatePayment, error) {
	defer 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)

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