package task

import (
	"context"
	"strconv"
	"time"

	"github.com/break/junhong_cmp_fiber/internal/infrastructure/integrationlog"
	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
)

// startGatewayAttempt 在实际调用 Gateway 前建立 Integration Log 尝试事实。
func startGatewayAttempt(ctx context.Context, repository *integrationlog.Repository, cardID uint, operation, scene string) (*model.IntegrationLog, error) {
	if repository == nil {
		return nil, errors.New(errors.CodeInternalError, "Gateway Integration Log 未配置")
	}
	resourceID := strconv.FormatUint(uint64(cardID), 10)
	triggerSource := constants.CardObservationSourcePolling
	triggerScene := scene
	return repository.Start(ctx, integrationlog.Attempt{
		Provider: constants.IntegrationProviderGateway, Direction: constants.IntegrationDirectionOutbound,
		Operation: operation, ResourceType: constants.AssetTypeIotCard, ResourceID: &resourceID,
		TriggerSource: &triggerSource, TriggerScene: &triggerScene,
		RequestSummary: map[string]any{"card_id": cardID}, Metadata: map[string]any{"scene": scene},
		InitialResult: constants.IntegrationResultPending,
	})
}

// completeGatewayAttempt 记录 Gateway 查询成功或明确失败，不把响应正文写入日志。
func completeGatewayAttempt(ctx context.Context, repository *integrationlog.Repository, attempt *model.IntegrationLog, success bool, startedAt time.Time) error {
	if repository == nil || attempt == nil {
		return errors.New(errors.CodeInternalError, "Gateway Integration Log 尝试不存在")
	}
	result := constants.IntegrationResultFailed
	if success {
		result = constants.IntegrationResultSuccess
	}
	_, err := repository.Complete(ctx, attempt.IntegrationID, integrationlog.Completion{
		Result: result, DurationMS: time.Since(startedAt).Milliseconds(), StateChanged: false,
		ResponseSummary: map[string]any{"success": success},
	})
	return err
}
