package main

import (
	"crypto/rand"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"

	_ "github.com/lib/pq"
)

func main() {
	db, err := sql.Open("postgres", os.Getenv("DATABASE_CONNECTION_STRING")+"?sslmode=disable")
	if err != nil {
		panic(err)
	}
	if err := db.Ping(); err != nil {
		panic(err)
	}

	_, err = db.Exec(`CREATE TABLE IF NOT EXISTS hits (
		id BIGSERIAL PRIMARY KEY,
		ts TIMESTAMPTZ NOT NULL DEFAULT NOW(),
		path TEXT NOT NULL,
		payload TEXT NOT NULL
	)`)
	if err != nil {
		panic(err)
	}

	hostname, _ := os.Hostname()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Printf("%s %s %s %s\n", r.Method, r.URL.Path, r.RemoteAddr, r.UserAgent())

		buf := make([]byte, 128)
		rand.Read(buf)
		payload := hex.EncodeToString(buf)
		ts := time.Now()

		var id int64
		err := db.QueryRow(
			`INSERT INTO hits (ts, path, payload) VALUES ($1, $2, $3) RETURNING id`,
			ts, r.URL.Path, payload,
		).Scan(&id)
		if err != nil {
			fmt.Printf("error inserting: %s\n", err)
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(map[string]any{
			"id":      id,
			"ts":      ts,
			"path":    r.URL.Path,
			"payload":  payload[:16],
			"hostname": hostname,
		})
	})

	fmt.Println("listening on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic(err)
	}
}
