package callback

import (
	"context"
	"time"

	"github.com/bytedance/sonic"
	"github.com/gofiber/fiber/v2"
	"go.uber.org/zap"

	cardapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
	carddomain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation"
	"github.com/break/junhong_cmp_fiber/internal/infrastructure/carriercallback"
	"github.com/break/junhong_cmp_fiber/internal/infrastructure/integrationlog"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	apperrors "github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/middleware"
)

// CMCCRealnameHandler 处理中国移动实名成功 JSON 回调。
type CMCCRealnameHandler struct {
	translator  *carriercallback.CMCCRealnameTranslator
	resolver    *carriercallback.CMCCCardResolver
	integration *integrationlog.Repository
	observation *cardapp.Service
	series      ResourceSeriesCompleter
	config      SystemConfigReader
	logger      *zap.Logger
}

// NewCMCCRealnameHandler 创建中国移动实名回调 Handler。
func NewCMCCRealnameHandler(translator *carriercallback.CMCCRealnameTranslator, resolver *carriercallback.CMCCCardResolver, integration *integrationlog.Repository, observation *cardapp.Service, series ResourceSeriesCompleter, config SystemConfigReader, logger *zap.Logger) *CMCCRealnameHandler {
	return &CMCCRealnameHandler{translator: translator, resolver: resolver, integration: integration, observation: observation, series: series, config: config, logger: logger}
}

// Realname 接收中国移动实名结果并返回固定成功应答。
// POST /api/callback/carriers/cmcc/realname
func (h *CMCCRealnameHandler) Realname(c *fiber.Ctx) error {
	startedAt := time.Now()
	enabled, err := carrierCallbackEnabled(c.UserContext(), h.config, constants.SystemConfigCarrierCallbackCMCCRealnameEnabled)
	if err != nil {
		if h.logger != nil {
			h.logger.Error("读取移动实名回调启停配置失败，已按关闭处理并返回成功", zap.Error(err))
		}
		return sendCMCCSuccess(c, startedAt)
	}
	if !enabled {
		if err := recordDisabledCarrierCallback(c.UserContext(), h.integration, constants.IntegrationProviderCMCC, constants.IntegrationOperationCMCCRealnameCallback, "cmcc-realname", c.Body(), c.Get("Content-Type")); err != nil && h.logger != nil {
			h.logger.Error("移动实名回调已关闭，但留痕失败", zap.Error(err))
		}
		return sendCMCCSuccess(c, startedAt)
	}
	if err := h.process(c.UserContext(), c.Body(), c.Get("Content-Type")); err != nil && h.logger != nil {
		h.logger.Error("处理移动实名回调失败，已按运营商约定返回成功", zap.Error(err))
	}
	return sendCMCCSuccess(c, startedAt)
}

func (h *CMCCRealnameHandler) process(ctx context.Context, body []byte, contentType string) error {
	if h == nil || h.translator == nil || h.resolver == nil || h.integration == nil || h.observation == nil {
		return apperrors.New(apperrors.CodeInternalError, "移动实名回调能力未完整配置")
	}
	translated, translateErr := h.translator.Translate(body)
	idempotencyKey := cmccIdempotencyKey(body, translated)
	integrationID := "cmcc-realname:" + shortHash(idempotencyKey)
	requestID := middleware.GetRequestIDFromContext(ctx)
	log, created, err := h.integration.RecordInbound(ctx, integrationlog.InboundAttempt{
		IntegrationID: integrationID, IdempotencyKey: idempotencyKey,
		Provider: constants.IntegrationProviderCMCC, Operation: constants.IntegrationOperationCMCCRealnameCallback,
		ResourceType: constants.CardObservationResourceTypeCard, ResourceKey: optionalHashedResourceKey(translated.ICCID),
		ExternalID: translated.BusiSeq, RawPayload: body, ContentType: contentType, RequestID: requestID, CorrelationID: requestID,
	})
	if err != nil {
		if isAppConflict(err) {
			return h.recordConflict(ctx, body, contentType, idempotencyKey, translated, requestID)
		}
		return err
	}
	if !created {
		if log.Result != constants.IntegrationResultPending {
			return nil
		}
		claimed, claimErr := h.integration.ClaimExpiredInboundPending(ctx, log.IntegrationID, constants.IntegrationInboundProcessingLease)
		if claimErr != nil || !claimed {
			return claimErr
		}
	}
	if translateErr != nil {
		return h.complete(ctx, log.IntegrationID, constants.IntegrationResultInvalidPayload, false, "报文或业务结果无效")
	}
	cards, err := h.resolver.Resolve(ctx, translated.ICCID)
	if err != nil {
		return h.fail(ctx, log.IntegrationID, err)
	}
	if len(cards) == 0 {
		return h.complete(ctx, log.IntegrationID, constants.IntegrationResultNotFound, false, "精确列未找到卡")
	}
	if len(cards) > 1 {
		return h.complete(ctx, log.IntegrationID, constants.IntegrationResultConflict, false, "精确列匹配多张卡")
	}
	card := cards[0]
	decision, err := h.observation.ApplyCardObservation(ctx, carddomain.RealnameObservation{
		CardID: card.ID, Verified: true,
		Metadata: carddomain.ObservationMetadata{
			ObservationID: log.IntegrationID, Source: constants.CardObservationSourceCarrierCallback,
			Scene: constants.CardObservationSceneCarrierCallback, ObservedAt: time.Now().UTC(),
			RequestID: optionalStringValue(requestID), CorrelationID: optionalStringValue(requestID), UpstreamSummary: "移动实名成功",
		},
	})
	if err != nil {
		return h.fail(ctx, log.IntegrationID, err)
	}
	if h.series != nil {
		if err := h.series.CompleteResourceSeries(ctx, constants.CardObservationResourceTypeCard, uintString(card.ID), constants.CardObservationSyncTypeRealname); err != nil && h.logger != nil {
			h.logger.Warn("移动实名事实已应用但提前完成观测序列失败", zap.Uint("card_id", card.ID), zap.Error(err))
		}
	}
	return h.complete(ctx, log.IntegrationID, constants.IntegrationResultSuccess, decision.StatusChanged, "实名事实已幂等应用")
}

func (h *CMCCRealnameHandler) recordConflict(ctx context.Context, body []byte, contentType, baseKey string, translated carriercallback.CMCCRealnameTranslation, requestID *string) error {
	key := baseKey + ":conflict:" + shortHashBytes(body)
	log, created, err := h.integration.RecordInbound(ctx, integrationlog.InboundAttempt{IntegrationID: "cmcc-realname-conflict:" + shortHash(key), IdempotencyKey: key, Provider: constants.IntegrationProviderCMCC, Operation: constants.IntegrationOperationCMCCRealnameCallback, ResourceType: constants.CardObservationResourceTypeCard, ResourceKey: optionalHashedResourceKey(translated.ICCID), ExternalID: translated.BusiSeq, RawPayload: body, ContentType: contentType, RequestID: requestID, CorrelationID: requestID})
	if err != nil {
		return err
	}
	if !created {
		if log.Result != constants.IntegrationResultPending {
			return nil
		}
		claimed, claimErr := h.integration.ClaimExpiredInboundPending(ctx, log.IntegrationID, constants.IntegrationInboundProcessingLease)
		if claimErr != nil || !claimed {
			return claimErr
		}
	}
	return h.complete(ctx, log.IntegrationID, constants.IntegrationResultConflict, false, "同一幂等语义对应不同载荷")
}

func (h *CMCCRealnameHandler) complete(ctx context.Context, integrationID, result string, changed bool, reason string) error {
	_, err := h.integration.Complete(ctx, integrationID, integrationlog.Completion{Result: result, HTTPStatus: fiber.StatusOK, StateChanged: changed, ResponseSummary: map[string]any{"reason": reason}})
	return err
}

func (h *CMCCRealnameHandler) fail(ctx context.Context, integrationID string, original error) error {
	if err := h.complete(ctx, integrationID, constants.IntegrationResultFailed, false, "内部处理失败"); err != nil && h.logger != nil {
		h.logger.Error("移动实名回调失败终态写入失败", zap.String("integration_id", integrationID), zap.Error(err))
	}
	return original
}

func cmccIdempotencyKey(body []byte, translated carriercallback.CMCCRealnameTranslation) string {
	if translated.BusiSeq != "" {
		return "cmcc-external:" + shortHash(translated.BusiSeq)
	}
	return "cmcc-body:" + shortHashBytes(body)
}

type cmccSuccessResponse struct {
	Code      int    `json:"code"`
	Message   string `json:"msg"`
	Timestamp string `json:"timestamp"`
}

func sendCMCCSuccess(c *fiber.Ctx, startedAt time.Time) error {
	body, err := sonic.Marshal(cmccSuccessResponse{Code: 200, Message: "success", Timestamp: startedAt.Format("2006-01-02 15:04:05")})
	if err != nil {
		return apperrors.Wrap(apperrors.CodeInternalError, err, "生成移动回调应答失败")
	}
	c.Type("json", "utf-8")
	return c.Status(fiber.StatusOK).Send(body)
}
