// alerts_mapper.go maps alert rows into weather model payloads.
// Layer: adapters/outbound/postgres alerts feature.
package postgres

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

func mapAlertRunParentRow(row alertRunParentRow) model.WeatherAlertRun {
	return model.WeatherAlertRun{
		LocationID:   stringValue(row.LocationID),
		LocationName: stringValue(row.LocationName),
		AsOf:         row.AsOf.UTC(),
		Latitude:     float64Ptr(row.Latitude),
		Longitude:    float64Ptr(row.Longitude),
	}
}

func mapAlertRow(row alertRow) indexedAlert {
	return indexedAlert{
		Index: row.AlertIndex,
		Alert: model.WeatherAlert{
			ID:              row.AlertID,
			Event:           stringValue(row.Event),
			Headline:        stringValue(row.Headline),
			Severity:        stringValue(row.Severity),
			Urgency:         stringValue(row.Urgency),
			Certainty:       stringValue(row.Certainty),
			Status:          stringValue(row.Status),
			MessageType:     stringValue(row.MessageType),
			Category:        stringValue(row.Category),
			Response:        stringValue(row.Response),
			Description:     stringValue(row.Description),
			Instruction:     stringValue(row.Instruction),
			Sent:            timePtr(row.Sent),
			Effective:       timePtr(row.Effective),
			Onset:           timePtr(row.Onset),
			Expires:         timePtr(row.Expires),
			AreaDescription: stringValue(row.AreaDescription),
			SenderName:      stringValue(row.SenderName),
		},
	}
}

func mapAlertReferenceRow(row alertReferenceRow) indexedAlertReference {
	return indexedAlertReference{
		AlertIndex: row.AlertIndex,
		Reference: model.AlertReference{
			ID:         stringValue(row.ID),
			Identifier: stringValue(row.Identifier),
			Sender:     stringValue(row.Sender),
			Sent:       timePtr(row.Sent),
		},
	}
}

func attachAlertReferences(alerts []indexedAlert, references []indexedAlertReference) []model.WeatherAlert {
	refsByAlertIndex := make(map[int][]model.AlertReference, len(alerts))
	for _, ref := range references {
		refsByAlertIndex[ref.AlertIndex] = append(refsByAlertIndex[ref.AlertIndex], ref.Reference)
	}

	out := make([]model.WeatherAlert, 0, len(alerts))
	for _, alert := range alerts {
		mapped := alert.Alert
		if refs := refsByAlertIndex[alert.Index]; len(refs) > 0 {
			mapped.References = refs
		}
		out = append(out, mapped)
	}
	return out
}
