package main

import (
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
	"path/filepath"
)

func main() {
	err := http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		u, p, ok := r.BasicAuth()
		if !ok {
			panic("no basic auth")
		}

		if p != "" {
			panic("password should be empty")
		}

		if u != "test" {
			panic("token must be set to 'test'")
		}

		eventsFp := filepath.Join("/events", fmt.Sprintf("%s.json", r.URL.Path))

		eventsF, err := os.OpenFile(eventsFp, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
		if err != nil {
			panic(err)
		}
		defer eventsF.Close()

		_, err = io.Copy(eventsF, r.Body)
		if err != nil {
			panic(err)
		}

		w.WriteHeader(http.StatusCreated)
	}))
	if !errors.Is(err, net.ErrClosed) {
		panic(err)
	}
}
