package router

import (
	"time"

	"verification-platform-backend/internal/middleware"
	"verification-platform-backend/internal/router/agent"
	"verification-platform-backend/internal/router/app"
	"verification-platform-backend/internal/router/admin"
	"verification-platform-backend/internal/router/extension"
	"verification-platform-backend/internal/router/frontend"
	"verification-platform-backend/internal/router/install"
	"verification-platform-backend/pkg/response"

	"github.com/gin-gonic/gin"
)

func SetupRoutes(r *gin.Engine) {
	r.Use(middleware.Cors())
	r.Use(middleware.Logger())

	r.GET("/health", func(c *gin.Context) {
		response.Success(c, gin.H{
			"status": "ok",
			"time":   time.Now().Format(time.RFC3339),
		})
	})

	install.SetupRoutes(r)

	frontend.SetupRoutes(r)

	api := r.Group("/api/v1")
	{
		devGroup := api.Group("/dev")
		{
			devGroup.Use(middleware.JWT())
			devGroup.Use(middleware.AdminAuth())
			admin.SetupRoutes(devGroup)
			admin.SetupRoutesWithoutPackage(devGroup)
		}

		agentGroup := api.Group("/agent")
		{
			agentGroup.Use(middleware.JWT())
			agentGroup.Use(middleware.AgentAuth())
			agent.SetupAgentRoutes(agentGroup)
		}

		appGroup := api.Group("/app/:appKey")
		{
			appGroup.Use(app.AppCryptoMiddleware())
			appGroup.Use(app.ResponseEncryption())
			app.SetupInfoRoutes(appGroup)
		}

		appGroupWithStatusCheck := api.Group("/app/:appKey")
		{
			appGroupWithStatusCheck.Use(middleware.CheckAppStatus())
			appGroupWithStatusCheck.Use(app.AppCryptoMiddleware())
			appGroupWithStatusCheck.Use(app.ResponseEncryption())
			app.SetupRoutes(appGroupWithStatusCheck)
			app.SetupAuthUserRoutes(appGroupWithStatusCheck)
			app.SetupDevicePublicRoutes(appGroupWithStatusCheck)
		}

		appAuthGroup := api.Group("/app/:appKey")
		{
			appAuthGroup.Use(middleware.JWT())
			appAuthGroup.Use(middleware.CheckAppStatus())
			appAuthGroup.Use(app.AppCryptoMiddleware())
			appAuthGroup.Use(app.ResponseEncryption())
			app.SetupCloudRoutes(appAuthGroup)
			app.SetupAuthRoutes(appAuthGroup)
		}

		extGroup := api.Group("")
		{
			extension.SetupRoutes(extGroup)
		}
	}
}
