package routes

import (
	"net/http"
	"time"

	"service/internal/infrastructure/cache"
	"service/internal/infrastructure/config"
	"service/internal/infrastructure/transport/http/middleware"

	authHttp "service/internal/infrastructure/transport/http/handlers/main/auth"
	healthHttp "service/internal/infrastructure/transport/http/handlers/main/health"
	roleHttp "service/internal/infrastructure/transport/http/handlers/main/master/roles"

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

// ModuleHandlers menampung seluruh HTTP handler opsional dari berbagai modul.
// Jika sebuah handler bernilai nil, maka rutenya akan otomatis diabaikan (disabled).
type ModuleHandlers struct {
	Auth           *authHttp.AuthHandler
	RolePages      *roleHttp.RolPagesHandler
	RolePermission *roleHttp.RolPermissionHandler
	RoleMaster     *roleHttp.RoleMasterHandler
}

// SetupRoutes mendaftarkan seluruh endpoint API secara dinamis berdasarkan
// modul-modul yang aktif (tidak nil) pada aplikasi.
func SetupRoutes(
	engine *gin.Engine,
	cfg *config.Config,
	cacheManager *cache.Manager,
	healthHandler *healthHttp.HealthHandler,
	h *ModuleHandlers,
) {
	// Handle 405 Method Not Allowed for better client feedback
	engine.HandleMethodNotAllowed = true

	// Health check endpoints - using consistent http.Status constants
	engine.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":    "healthy",
			"timestamp": time.Now().UTC(),
			"service":   "service-general",
			"version":   "1.0.0",
		})
	})

	// Comprehensive health check with dependencies
	engine.GET("/health/complete", healthHandler.HealthCheckComplete)

	// Database health check
	engine.GET("/health/database", healthHandler.HealthCheckDatabase)

	// Redis/cache health check
	engine.GET("/health/cache", healthHandler.HealthCheckCache)

	// External services health check
	engine.GET("/health/external", healthHandler.HealthCheckExternal)

	// Minio service
	engine.GET("/health/minio", healthHandler.HealthCheckMinio)
	engine.POST("/health/minio/upload", healthHandler.TestUploadMinio)

	// All databases health check
	// engine.GET("/health/databases", healthHandler.HealthCheckAllDatabases)

	// Readiness check
	engine.GET("/ready", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":    "ready",
			"timestamp": time.Now().UTC(),
		})
	})

	// Liveness check
	engine.GET("/live", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":    "alive",
			"timestamp": time.Now().UTC(),
		})
	})

	// Redirect otomatis dari /swagger ke /swagger/index.html
	engine.GET("/swagger", func(c *gin.Context) {
		c.Redirect(http.StatusFound, "/swagger/index.html")
	})

	// Endpoint untuk Swagger UI
	engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// API v1 routes
	v1 := engine.Group("/api/v1")
	{
		// Register auth routes (Public)
		if h.Auth != nil {
			h.Auth.RegisterRoutes(v1)
		}

		// Private routes (Membutuhkan Autentikasi)
		protected := v1.Group("")
		protected.Use(middleware.AuthMiddleware(cfg, cacheManager))
		{
			if h.Auth != nil {
				h.Auth.RegisterProtectedRoutes(protected)
			}

			// --- Routes Modul Master ---
			if h.RolePages != nil {
				h.RolePages.RegisterRoutes(protected)
			}
			if h.RolePermission != nil {
				h.RolePermission.RegisterRoutes(protected)
			}
			if h.RoleMaster != nil {
				h.RoleMaster.RegisterRoutes(protected)
			}
		}
	}
}
