package server

import (
	"strings"

	"git.pbiernat.dev/egommerce/go-api-pkg/fluentd"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
)

var (
	defaultCORS = cors.New(cors.Config{
		AllowOrigins:     "*",
		AllowCredentials: true,
		AllowMethods:     "GET, POST, PATCH, PUT, DELETE, OPTIONS",
		AllowHeaders:     "Accept, Authorization, Content-Type, Vary, X-Request-Id",
	})
)

func SetupMiddlewares(s *Server) {
	s.App.Use(defaultCORS)
	s.App.Use(LoggingMiddleware(s.log))
}

func SetupRoutes(s *Server) {
	s.App.Options("*", defaultCORS)

	s.App.Get("/health", s.HealthHandler)
	s.App.Get("/config", s.ConfigHandler)

	api := s.App.Group("/api")
	v1 := api.Group("/v1")
	v1.Post("/login", s.LoginHandler)
	v1.All("/traefik", s.TraefikHandler)
}

// Middlewares
func LoggingMiddleware(log *fluentd.Logger) func(c *fiber.Ctx) error {
	return func(c *fiber.Ctx) error {
		path := string(c.Request().URI().Path())
		if strings.Contains(path, "/health") {
			return c.Next()
		}

		if strings.Contains(path, "/traefik") {
			log.Log("Request: %s, Headers: %v, remote: %s, via: %s",
				c.Request().URI().String(),
				c.GetRespHeaders(),
				c.Context().RemoteIP().String(),
				string(c.Context().UserAgent()))

			return c.Next()
		}

		log.Log("Request: %s, remote: %s, via: %s",
			c.Request().URI().String(),
			c.Context().RemoteIP().String(),
			string(c.Context().UserAgent()))

		return c.Next()
	}
}
