package analytics

import (
	"context"
	"time"

	"github.com/nexuscrm/shared/pkg/constants"
	zlog "github.com/rs/zerolog/log"
)

// logRollupStageTiming emits a structured stage-timing log for a single step of
// the rollup processing loop. It mirrors records.logRecordStageTiming so the two
// can be correlated by request_id, and exists to break the previously-silent
// gap inside processAffectedRollups (lockParent / CalculateRollup / UpdateDerived)
// where 20s+ of wall time was disappearing with no instrumentation.
func logRollupStageTiming(ctx context.Context, stage, parentObj, parentID, rollupField string, started time.Time, err error) {
	requestID, _ := ctx.Value(constants.ContextKeyRequestID).(string)
	elapsed := time.Since(started).Milliseconds()
	if err != nil {
		zlog.Error().
			Str("event", "rollup_stage_timing").
			Str("stage", stage).
			Str("request_id", requestID).
			Str("parent_object", parentObj).
			Str("parent_id", parentID).
			Str("rollup_field", rollupField).
			Str("status", "error").
			Int64("elapsed_ms", elapsed).
			Err(err).
			Msg("Rollup stage timing")
		return
	}
	zlog.Debug().
		Str("event", "rollup_stage_timing").
		Str("stage", stage).
		Str("request_id", requestID).
		Str("parent_object", parentObj).
		Str("parent_id", parentID).
		Str("rollup_field", rollupField).
		Str("status", "success").
		Int64("elapsed_ms", elapsed).
		Msg("Rollup stage timing")
}
