package http

import (
	"context"
	"fmt"
	"github.com/gofiber/fiber/v2"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/middleware"
)

type ServerConfig struct {
	Controllers []Controller
}

type Server struct {
	Controllers []Controller
	app         *fiber.App
}

func NewServer(config ServerConfig) *Server {
	app := fiber.New()
	app.Use("/amocrm", middleware.JWTAuth())
	app.Use("/webhook", func(c *fiber.Ctx) error {
		return c.Next()
	})

	s := &Server{
		Controllers: config.Controllers,
		app:         app,
	}

	s.registerRoutes()

	return s
}

func (s *Server) Start(addr string) error {
	if err := s.app.Listen(addr); err != nil {
		return err
	}
	return nil
}

func (s *Server) Shutdown(ctx context.Context) error {
	return s.app.Shutdown()
}

func (s *Server) registerRoutes() {
	for _, c := range s.Controllers {
		router := s.app.Group(c.Name())
		c.Register(router)
	}
}

type Controller interface {
	Register(router fiber.Router)
	Name() string
}

func (s *Server) ListRoutes() {
	fmt.Println("Registered routes:")
	for _, stack := range s.app.Stack() {
		for _, route := range stack {
			fmt.Printf("%s %s\n", route.Method, route.Path)
		}
	}
}
