package routes

import (
	"git.threefold.info/herocode/heroagent/pkg/servers/ui/controllers"
	"git.threefold.info/herocode/heroagent/pkg/servers/ui/models"
	"github.com/gofiber/fiber/v2"
)

// SetupRoutes configures the application's routes.
func SetupRoutes(app *fiber.App) {
	// Initialize services and controllers
	// For now, using the mock process manager
	processManagerService := models.NewMockProcessManager()
	jobManagerService := models.NewMockJobManager()
	openrpcManagerService := models.NewOpenRPCManager()

	dashboardController := controllers.NewDashboardController()
	processController := controllers.NewProcessController(processManagerService)
	jobController := controllers.NewJobController(jobManagerService)
	authController := controllers.NewAuthController()
	openrpcController := controllers.NewOpenRPCController(openrpcManagerService)

	// --- Public Routes ---
	// Login and Logout
	app.Get("/login", authController.ShowLoginPage)
	app.Post("/login", authController.HandleLogin)
	app.Get("/logout", authController.HandleLogout)

	// --- Authenticated Routes ---
	// TODO: Add middleware here to protect routes that require authentication.
	// For example:
	// authenticated := app.Group("/", authMiddleware) // Assuming authMiddleware is defined
	// authenticated.Get("/", dashboardController.ShowDashboard)
	// authenticated.Get("/processes", processController.ShowProcessManager)
	// authenticated.Post("/processes/kill/:pid", processController.HandleKillProcess)

	// For now, routes are public for development ease
	app.Get("/", dashboardController.ShowDashboard)

	// Process management routes
	app.Get("/processes", processController.ShowProcessManager)
	app.Post("/processes/kill/:pid", processController.HandleKillProcess)

	// Job management routes
	app.Get("/jobs", jobController.ShowJobsPage)
	app.Get("/jobs/:id", jobController.ShowJobDetails)

	// OpenRPC UI routes
	app.Get("/rpcui", openrpcController.ShowOpenRPCUI)
	app.Post("/api/rpcui/execute", openrpcController.ExecuteRPC)

	// Debug routes
	app.Get("/debug", func(c *fiber.Ctx) error {
		// Get all data from the jobs page to debug
		jobManagerService := models.NewMockJobManager()
		jobs, _ := jobManagerService.GetAllJobs()

		// Create debug data
		debugData := fiber.Map{
			"Title": "Debug Page",
			"Jobs":  jobs,
			"TemplateData": fiber.Map{
				"TotalJobs":     len(jobs),
				"ActiveJobs":    0,
				"CompletedJobs": 0,
				"ErrorJobs":     0,
			},
		}

		// Return as JSON instead of rendering a template
		return c.JSON(debugData)
	})
}

// TODO: Implement authMiddleware
// func authMiddleware(c *fiber.Ctx) error {
// 	// Check for session/token
// 	// If not authenticated, redirect to /login
// 	// If authenticated, c.Next()
// 	// Example:
// 	// if c.Cookies("session_token") == "" {
// 	// 	return c.Redirect("/login")
// 	// }
// 	return c.Next()
// }
