package fieldz

import (
	"net/http"
	"time"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/api"
)

const (
	AgentKeyFieldName        = "agent_key"
	LastConnectedAtFieldName = "recently_connected_at"
	SecondsAgoFieldName      = "seconds_ago"
	AttributesFieldName      = "attrs"
	ResponseHeadersFieldName = "headers"
)

// Field represents a single key value pair for logging and error tracking purposes.
type Field struct {
	Key   string
	Value any
}

func (f *Field) IsEmpty() bool {
	return f.Key == "" && f.Value == nil
}

func New(key string, value any) Field {
	return Field{Key: key, Value: value}
}

func ToMap(fields []Field) map[string]any {
	m := make(map[string]any, len(fields))
	for _, field := range fields {
		if field.IsEmpty() {
			continue
		}
		m[field.Key] = field.Value
	}
	return m
}

func AgentKey(agentKey api.AgentKey) Field {
	return Field{Key: AgentKeyFieldName, Value: agentKey}
}

func LastConnectedAt(timestamp time.Time) Field {
	return Field{Key: LastConnectedAtFieldName, Value: timestamp.UTC()}
}

func SecondsAgo(duration time.Duration) Field {
	return Field{Key: SecondsAgoFieldName, Value: duration}
}

func ResponseHeaders(h http.Header) Field {
	return Field{Key: ResponseHeadersFieldName, Value: h}
}
