package gateway

import (
	"lingniu-vehicle-ingest/go/vehicle-gateway/internal/envelope"
	"lingniu-vehicle-ingest/go/vehicle-gateway/internal/realtime"
)

const (
	gatewayFieldsPublished          = "published"
	gatewayFieldsDelegated          = "delegated_to_bridge"
	gatewayFieldsSkippedNonRealtime = "skipped_non_realtime"
	gatewayFieldsSkippedMissing     = "skipped_missing_fields"
	gatewayFieldsPublishError       = "publish_error"
)

func gatewayFieldsEnvelope(env envelope.FrameEnvelope) (envelope.FrameEnvelope, string, bool) {
	if !envelope.IsRealtimeTelemetryFrame(env) {
		return envelope.FrameEnvelope{}, gatewayFieldsSkippedNonRealtime, false
	}
	fieldsEnv, ok := realtime.BuildFieldsEnvelope(env)
	if !ok {
		return envelope.FrameEnvelope{}, gatewayFieldsSkippedMissing, false
	}
	return fieldsEnv, gatewayFieldsPublished, true
}

func gatewayDelegatedFields(env envelope.FrameEnvelope) (int, string, bool) {
	if !envelope.IsRealtimeTelemetryFrame(env) {
		return 0, gatewayFieldsSkippedNonRealtime, false
	}
	if len(env.ParsedFields) == 0 {
		return 0, gatewayFieldsSkippedMissing, false
	}
	return len(env.ParsedFields), gatewayFieldsDelegated, true
}

func canonicalRawEnvelope(env envelope.FrameEnvelope) envelope.FrameEnvelope {
	env.EventKind = envelope.EventKindRaw
	env.Parsed = nil
	env.Fields = nil
	return env
}
