package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	numerus "dev.tandem.ws/tandem/numerus/pkg"
)

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

	srv := http.Server{
		Addr:         ":8080",
		Handler:      numerus.NewRouter(db),
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
		IdleTimeout:  2 * time.Minute,
	}

	go func() {
		log.Printf("INFO - listening on %s\n", srv.Addr)
		if err := srv.ListenAndServe(); err != http.ErrServerClosed {
			log.Fatalf("http server: %v", err)
		}
	}()

	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
	<-sigCh
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	log.Print("INFO - stopping server")
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal(err)
	}
}
