package router

import (
	"api_es/internal/config"
	"api_es/pkg/logger"
	"encoding/json"
	"net/http"

	"api_es/internal/handler"
	appMiddleware "api_es/internal/middleware"

	"github.com/go-chi/chi/v5"
	"gorm.io/gorm"
)

func SetupRouter(db *gorm.DB, config *config.Config) http.Handler {
	zapLogger := logger.Get()
	zapLogger.Debug("Start setup rounting")
	r := chi.NewRouter()

	// Initialize logger
	baseLogger := logger.NewWrapper(logger.Get())

	setupMiddlewares(r)

	// Health check
	r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"status": "healthy"})
	})

	h := handler.NewAllHandler(db, config)

	// Health routes
	r.Route("/", func(r chi.Router) {
		r.Get("/health", h.HealthHandler().HealthCheck)
		r.Get("/check", h.HealthHandler().Check)
	})

	// router.go (обновляем секцию auth routes)
	r.Route("/auth", func(r chi.Router) {
		r.Post("/register", h.UserHandler().Register)
		r.Post("/login", h.UserHandler().Login)
		r.Post("/logout", h.UserHandler().Logout)
		r.Post("/refresh", h.UserHandler().RefreshToken)
	})

	r.Route("/users", func(r chi.Router) {
		r.Use(appMiddleware.AuthMiddleware)

		r.Get("/profile", h.UserHandler().GetProfile)
		r.Put("/profile", h.UserHandler().UpdateProfile)

		// Admin routes
		r.With(appMiddleware.AdminMiddleware).Get("/", h.UserHandler().ListUsers)
		r.With(appMiddleware.AdminMiddleware).Get("/{id}", h.UserHandler().GetUser)
	})

	zapLogger.Debug("End setup routing")

	// Логируем все зарегистрированные маршруты
	routeLogger := logger.NewRouteLogger(baseLogger)
	routeLogger.LogRoutes(r)

	return r
}
