package envelope

import "time"

const (
	MaxFutureEventSkew         = 10 * time.Minute
	MinPlausibleReceivedTimeMS = 1577836800000 // 2020-01-01T00:00:00Z
)

const (
	EventTimeReasonEventTime            = "event_time"
	EventTimeReasonReceivedMissingEvent = "received_time_missing_event"
	EventTimeReasonReceivedFutureEvent  = "received_time_future_event"
)

func NormalizedEventTimeMS(env FrameEnvelope) (int64, bool) {
	eventMS, _, ok := NormalizedEventTimeMSWithReason(env)
	return eventMS, ok
}

func NormalizedEventTimeMSWithReason(env FrameEnvelope) (int64, string, bool) {
	eventMS := env.EventTimeMS
	receivedMS := env.ReceivedAtMS
	if eventMS <= 0 {
		return receivedMS, EventTimeReasonReceivedMissingEvent, receivedMS > 0
	}
	if receivedMS >= MinPlausibleReceivedTimeMS && eventMS > receivedMS+MaxFutureEventSkew.Milliseconds() {
		return receivedMS, EventTimeReasonReceivedFutureEvent, true
	}
	return eventMS, EventTimeReasonEventTime, true
}
