package platform

import (
	"context"
	"encoding/json"
	"fmt"
)

func (s *ProductionStore) MetricDefinitions(ctx context.Context) ([]MetricDefinition, error) {
	rows, err := s.db.QueryContext(ctx, `SELECT metric_key,label,description,unit,category,value_type,protocols_json,searchable,chartable,alertable
FROM vehicle_metric_definition WHERE enabled=1 ORDER BY sort_order,metric_key`)
	if err != nil {
		return nil, fmt.Errorf("metric catalog unavailable; apply deploy/migrations/005_metric_catalog.sql: %w", err)
	}
	defer rows.Close()
	definitions := make([]MetricDefinition, 0, 16)
	byKey := map[string]int{}
	for rows.Next() {
		var definition MetricDefinition
		var protocols string
		if err := rows.Scan(&definition.Key, &definition.Label, &definition.Description, &definition.Unit, &definition.Category, &definition.ValueType, &protocols, &definition.Searchable, &definition.Chartable, &definition.Alertable); err != nil {
			return nil, err
		}
		if err := json.Unmarshal([]byte(protocols), &definition.Protocols); err != nil {
			return nil, fmt.Errorf("decode metric %s protocols: %w", definition.Key, err)
		}
		definition.SourceFields = map[string]string{}
		definitions = append(definitions, definition)
		byKey[definition.Key] = len(definitions) - 1
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	if len(definitions) == 0 {
		return nil, fmt.Errorf("metric catalog has no enabled definitions")
	}
	mappings, err := s.db.QueryContext(ctx, `SELECT m.metric_key,m.protocol,m.source_field
FROM vehicle_metric_protocol_mapping m JOIN vehicle_metric_definition d ON d.metric_key=m.metric_key AND d.enabled=1
ORDER BY m.metric_key,m.protocol`)
	if err != nil {
		return nil, err
	}
	defer mappings.Close()
	for mappings.Next() {
		var key, protocol, sourceField string
		if err := mappings.Scan(&key, &protocol, &sourceField); err != nil {
			return nil, err
		}
		if index, ok := byKey[key]; ok {
			definitions[index].SourceFields[protocol] = sourceField
		}
	}
	return definitions, mappings.Err()
}
