// observations_mapper.go maps observation rows into weather model payloads.
// Layer: adapters/outbound/postgres observations feature.
package postgres

import (
	"encoding/json"
	"strings"

	"gitea.maximumdirect.net/ejr/weatherfeeder/model"
)

func mapObservationParentRow(row observationParentRow) model.WeatherObservation {
	return model.WeatherObservation{
		StationID:               stringValue(row.StationID),
		StationName:             stringValue(row.StationName),
		Timestamp:               row.ObservedAt.UTC(),
		ConditionCode:           model.WMOCode(row.ConditionCode),
		IsDay:                   boolPtr(row.IsDay),
		TextDescription:         stringValue(row.TextDescription),
		TemperatureC:            float64Ptr(row.TemperatureC),
		DewpointC:               float64Ptr(row.DewpointC),
		WindDirectionDegrees:    float64Ptr(row.WindDirectionDegrees),
		WindSpeedKmh:            float64Ptr(row.WindSpeedKmh),
		WindGustKmh:             float64Ptr(row.WindGustKmh),
		BarometricPressurePa:    float64Ptr(row.BarometricPressurePa),
		VisibilityMeters:        float64Ptr(row.VisibilityMeters),
		RelativeHumidityPercent: float64Ptr(row.RelativeHumidityPercent),
		ApparentTemperatureC:    float64Ptr(row.ApparentTemperatureC),
	}
}

func mapObservationPresentWeatherRow(row observationPresentWeatherRow) (model.PresentWeather, error) {
	if !row.RawText.Valid || strings.TrimSpace(row.RawText.String) == "" {
		return model.PresentWeather{}, nil
	}

	var raw map[string]any
	if err := json.Unmarshal([]byte(row.RawText.String), &raw); err != nil {
		return model.PresentWeather{}, err
	}
	return model.PresentWeather{Raw: raw}, nil
}
