package main

import (
	"kontor-api-echo/pkg/handler"
	"kontor-api-echo/pkg/schema"
	"log"
	"os"

	echojwt "github.com/labstack/echo-jwt/v4"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func main() {
	log.SetOutput(os.Stdout)
	log.Println("Kontor started")

	if _, err := schema.GetDatabase(); err != nil {
		log.Fatal(err)
	}

	e := echo.New()
	e.GET("/health", handler.GetHealth)
	e.POST("/login", handler.Login)

	skipper := func(c echo.Context) bool {
		// Skip health check endpoint
		return c.Request().URL.Path == "/health"
	}

	e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
		LogStatus:   true,
		LogURI:      true,
		LogError:    true,
		HandleError: true,
		Skipper:     skipper,
		LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
			if v.Error == nil {
				log.Printf("REQUEST: uri: %v, status: %v\n", v.URI, v.Status)
			} else {
				log.Printf("REQUEST-ERROR: uri: %v, status: %v, err: %v\n", v.URI, v.Status, v.Error.Error())
			}
			return nil
		},
	}))

	group := e.Group("/api")
	group.Use(echojwt.WithConfig(echojwt.Config{SigningKey: []byte("secret")}))
	handler.SetupComicRoutes(group)
	handler.SetupMediaRoutes(group)

	e.Logger.Fatal(e.Start(":8400"))
	log.Println("Kontor finished")
}
