package database

import (
	"context"
	"database/sql"
	"fmt"
	"time"
)

// UpsertRadarWeather stores a realtime snapshot for a radar station.
// Table schema (expected):
//
//	CREATE TABLE IF NOT EXISTS radar_weather (
//	    id SERIAL PRIMARY KEY,
//	    alias TEXT NOT NULL,
//	    lat DOUBLE PRECISION NOT NULL,
//	    lon DOUBLE PRECISION NOT NULL,
//	    dt TIMESTAMPTZ NOT NULL,
//	    temperature DOUBLE PRECISION,
//	    humidity DOUBLE PRECISION,
//	    cloudrate DOUBLE PRECISION,
//	    visibility DOUBLE PRECISION,
//	    dswrf DOUBLE PRECISION,
//	    wind_speed DOUBLE PRECISION,
//	    wind_direction DOUBLE PRECISION,
//	    pressure DOUBLE PRECISION,
//	    created_at TIMESTAMPTZ DEFAULT now()
//	);
//	CREATE UNIQUE INDEX IF NOT EXISTS radar_weather_udx ON radar_weather(alias, dt);
func UpsertRadarWeather(
	ctx context.Context,
	db *sql.DB,
	alias string,
	lat, lon float64,
	dt time.Time,
	temperature, humidity, cloudrate, visibility, dswrf, windSpeed, windDir, pressure float64,
) error {
	const q = `
    INSERT INTO radar_weather (
        alias, lat, lon, dt,
        temperature, humidity, cloudrate, visibility, dswrf,
        wind_speed, wind_direction, pressure
    ) VALUES (
        $1,$2,$3,$4,
        $5,$6,$7,$8,$9,
        $10,$11,$12
    )
    ON CONFLICT (alias, dt)
    DO UPDATE SET
        lat = EXCLUDED.lat,
        lon = EXCLUDED.lon,
        temperature = EXCLUDED.temperature,
        humidity = EXCLUDED.humidity,
        cloudrate = EXCLUDED.cloudrate,
        visibility = EXCLUDED.visibility,
        dswrf = EXCLUDED.dswrf,
        wind_speed = EXCLUDED.wind_speed,
        wind_direction = EXCLUDED.wind_direction,
        pressure = EXCLUDED.pressure`

	_, err := db.ExecContext(ctx, q,
		alias, lat, lon, dt,
		temperature, humidity, cloudrate, visibility, dswrf,
		windSpeed, windDir, pressure,
	)
	if err != nil {
		return fmt.Errorf("upsert radar_weather (%s %s): %w", alias, dt.Format(time.RFC3339), err)
	}
	return nil
}
