package realtime

import (
	"time"

	"lingniu-vehicle-ingest/go/vehicle-gateway/internal/envelope"
)

type Snapshot struct {
	VehicleKey   string              `json:"vehicle_key"`
	VIN          string              `json:"vin"`
	Protocol     envelope.Protocol   `json:"protocol,omitempty"`
	Protocols    []envelope.Protocol `json:"protocols,omitempty"`
	EventID      string              `json:"event_id,omitempty"`
	EventTimeMS  int64               `json:"event_time_ms"`
	ReceivedAtMS int64               `json:"received_at_ms"`
	Fields       map[string]any      `json:"fields,omitempty"`
	FieldTimesMS map[string]int64    `json:"field_times_ms,omitempty"`
	Parsed       map[string]any      `json:"parsed,omitempty"`
	UpdatedAtMS  int64               `json:"updated_at_ms"`
}

func (s Snapshot) Lightweight() Snapshot {
	s.Parsed = nil
	return s
}

type OnlineStatus struct {
	VehicleKey     string              `json:"vehicle_key"`
	VIN            string              `json:"vin"`
	Protocol       envelope.Protocol   `json:"protocol,omitempty"`
	Online         bool                `json:"online"`
	LastSeenMS     int64               `json:"last_seen_ms"`
	OfflineAfterMS int64               `json:"offline_after_ms"`
	SourceEndpoint string              `json:"source_endpoint,omitempty"`
	Protocols      []envelope.Protocol `json:"protocols,omitempty"`
	TTLSeconds     int64               `json:"ttl_seconds"`
}

type OnlineListQuery struct {
	Protocol envelope.Protocol `json:"protocol,omitempty"`
	Limit    int               `json:"limit"`
	Offset   int               `json:"offset"`
}

type ProtocolPipelineSummary struct {
	Protocol     envelope.Protocol `json:"protocol"`
	IndexedCount int64             `json:"indexed_count"`
	OnlineCount  int64             `json:"online_count"`
	LatestSeenMS int64             `json:"latest_seen_ms"`
}

type PipelineSummary struct {
	Protocols []ProtocolPipelineSummary `json:"protocols"`
	UpdatedMS int64                     `json:"updated_ms"`
}

type Config struct {
	OnlineTTL time.Duration
}

func (c Config) ttl() time.Duration {
	if c.OnlineTTL <= 0 {
		return time.Minute
	}
	return c.OnlineTTL
}
