package main

import (
	"errors"
	"log"
	"net/http"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func main() {
	cfg := loadConfig()

	db, err := initDB(cfg)
	if err != nil {
		log.Fatalf("init db: %v", err)
	}
	defer db.Close()

	app := &App{
		db:  db,
		cfg: cfg,
		sessions: &SessionStore{
			tokens:   map[string]time.Time{},
			duration: 8 * time.Hour,
		},
		events: &EventHub{
			subscribers: map[int]chan struct{}{},
		},
	}

	e := echo.New()
	e.HideBanner = true
	e.HidePort = true
	e.Use(middleware.Recover())
	e.Use(middleware.Logger())
	e.Use(middleware.RequestID())
	e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins: []string{"*"},
		AllowMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions},
		AllowHeaders: []string{echo.HeaderContentType, echo.HeaderAuthorization},
	}))

	registerAPIRoutes(e, app)
	registerWebRoutes(e, cfg)

	addr := ":" + cfg.Port
	log.Printf("listening on %s", addr)
	if err := e.Start(addr); err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Fatalf("server error: %v", err)
	}
}
