package main

import (
	"context"
	"dev.tandem.ws/tandem/camper/pkg/database"
	"encoding/json"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"
)

type Temperature struct {
	Day float64 `json:"day"`
	Min float64 `json:"min"`
}

type Weather struct {
	ID int `json:"id"`
}

type Forecast struct {
	Timestamp   int64       `json:"dt"`
	Weather     []Weather   `json:"weather"`
	Temperature Temperature `json:"temp"`
}

type OpenWeatherMap struct {
	Forecasts []Forecast `json:"list"`
}

func main() {
	db, err := database.New(context.Background(), os.Getenv("CAMPER_DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	conn, err := db.Acquire(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Release()
	updateForecast(context.Background(), conn)
}

func updateForecast(ctx context.Context, conn *database.Conn) {
	if _, err := conn.Exec(ctx, "set role to admin"); err != nil {
		log.Fatal(err)
	}

	var stationURL string
	if err := conn.QueryRow(ctx, `
		select station_uri
		from weather_forecast
	`).Scan(
		&stationURL,
	); err != nil {
		log.Fatal(err)
	}

	resp, err := http.Get(stationURL)
	if err != nil {
		log.Fatal(err)
	}

	var result OpenWeatherMap
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}

	for _, forecast := range result.Forecasts {
		if _, err := conn.Exec(ctx, `
			update weather_forecast
			set weather_condition_id = $1
			  , day_temperature = $2
			  , min_temperature = $3
			  , forecasted_at = $4
			  , updated_at = current_timestamp
			where station_uri = $5
		`,
			strconv.Itoa(forecast.Weather[0].ID),
			forecast.Temperature.Day,
			forecast.Temperature.Min,
			time.Unix(forecast.Timestamp, 0),
			stationURL,
		); err != nil {
			log.Fatal(err)
		}
	}
}
