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"
	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/v2/bson"
	"go.uber.org/zap"
)

func (a *PaymentAPI) initiatePaymentsByQuote(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 batch payment initiation", 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, 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 batch payments", mutil.PLog(a.oph, r))
		return response.AccessDenied(a.logger, a.Name(), "payments write permission denied")
	}

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

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

	resp, err := a.client.InitiatePayments(ctx, req)
	if err != nil {
		a.logger.Warn("Failed to initiate batch payments", zap.Error(err), zap.String("organization_ref", orgRef.Hex()))
		return response.Auto(a.logger, a.Name(), err)
	}

	return sresponse.PaymentsResponse(a.logger, resp.GetPayments(), token)
}

func decodeInitiatePaymentsPayload(r *http.Request) (*srequest.InitiatePayments, error) {
	defer r.Body.Close()

	payload := &srequest.InitiatePayments{}
	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
}
