package callback

import (
	"context"
	"strconv"

	"github.com/gofiber/fiber/v2"

	"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"
)

// SystemConfigReader 提供运营商回调运行时开关读取能力。
type SystemConfigReader interface {
	Get(ctx context.Context, key string) (string, error)
}

func carrierCallbackEnabled(ctx context.Context, reader SystemConfigReader, key string) (bool, error) {
	if reader == nil {
		return false, apperrors.New(apperrors.CodeInternalError, "运营商回调启停配置未装配")
	}
	value, err := reader.Get(ctx, key)
	if err != nil {
		return false, apperrors.Wrap(apperrors.CodeInternalError, err, "读取运营商回调启停配置失败")
	}
	enabled, err := strconv.ParseBool(value)
	if err != nil {
		return false, apperrors.Wrap(apperrors.CodeInternalError, err, "运营商回调启停配置值无效")
	}
	return enabled, nil
}

func recordDisabledCarrierCallback(
	ctx context.Context,
	repository *integrationlog.Repository,
	provider string,
	operation string,
	integrationPrefix string,
	body []byte,
	contentType string,
) error {
	if repository == nil {
		return apperrors.New(apperrors.CodeInternalError, "运营商回调留痕能力未配置")
	}
	payloadHash := shortHashBytes(body)
	key := integrationPrefix + "-disabled-body:" + payloadHash
	requestID := middleware.GetRequestIDFromContext(ctx)
	log, created, err := repository.RecordInbound(ctx, integrationlog.InboundAttempt{
		IntegrationID:  integrationPrefix + "-disabled:" + shortHash(key),
		IdempotencyKey: key,
		Provider:       provider,
		Operation:      operation,
		ResourceType:   constants.CardObservationResourceTypeCard,
		RawPayload:     body,
		ContentType:    contentType,
		RequestID:      requestID,
		CorrelationID:  requestID,
	})
	if err != nil {
		return err
	}
	if !created {
		if log == nil || log.Result != constants.IntegrationResultPending {
			return nil
		}
		claimed, claimErr := repository.ClaimExpiredInboundPending(ctx, log.IntegrationID, constants.IntegrationInboundProcessingLease)
		if claimErr != nil || !claimed {
			return claimErr
		}
	}
	_, err = repository.Complete(ctx, log.IntegrationID, integrationlog.Completion{
		Result:          constants.IntegrationResultIgnored,
		HTTPStatus:      fiber.StatusOK,
		ResponseSummary: map[string]any{"reason": "后台配置已关闭该运营商回调"},
	})
	return err
}
