package paymentapiimp

import (
	"context"
	"encoding/json"
	"net/http"
	"time"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/discovery"
	"github.com/tech/sendico/pkg/merrors"
	me "github.com/tech/sendico/pkg/messaging/envelope"
	"github.com/tech/sendico/pkg/model"
	"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"
)

const discoveryLookupTimeout = 3 * time.Second

func (a *PaymentAPI) listDiscoveryRegistry(r *http.Request, account *model.Account, _ *sresponse.TokenData) http.HandlerFunc {
	if a.discovery == nil {
		return response.Internal(a.logger, a.Name(), merrors.Internal("discovery client is not configured"))
	}

	orgRef, err := a.oph.GetRef(r)
	if err != nil {
		a.logger.Warn("Failed to parse organization reference for discovery registry", 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.ActionRead)
	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 listing discovery registry", mutil.PLog(a.oph, r))
		return response.AccessDenied(a.logger, a.Name(), "payments read permission denied")
	}

	reqCtx, cancel := context.WithTimeout(ctx, discoveryLookupTimeout)
	defer cancel()

	payload, err := a.discovery.Lookup(reqCtx)
	if err != nil {
		a.logger.Warn("Failed to fetch discovery registry", zap.Error(err))
		return response.Auto(a.logger, a.Name(), err)
	}

	return response.Ok(a.logger, payload)
}

func (a *PaymentAPI) getDiscoveryRefresh(r *http.Request, account *model.Account, _ *sresponse.TokenData) http.HandlerFunc {
	if a.refreshConsumer == nil {
		return response.Internal(a.logger, a.Name(), merrors.Internal("discovery refresh consumer is not configured"))
	}

	orgRef, err := a.oph.GetRef(r)
	if err != nil {
		a.logger.Warn("Failed to parse organization reference for discovery refresh", 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.ActionRead)
	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 listing discovery refresh", mutil.PLog(a.oph, r))
		return response.AccessDenied(a.logger, a.Name(), "payments read permission denied")
	}

	a.refreshMu.RLock()
	payload := a.refreshEvent
	a.refreshMu.RUnlock()

	return response.Ok(a.logger, payload)
}

func (a *PaymentAPI) handleRefreshEvent(_ context.Context, env me.Envelope) error {
	var payload discovery.RefreshEvent
	if err := json.Unmarshal(env.GetData(), &payload); err != nil {
		a.logger.Warn("Failed to decode discovery refresh payload", zap.Error(err))
		return err
	}
	a.refreshMu.Lock()
	a.refreshEvent = &payload
	a.refreshMu.Unlock()
	return nil
}
