package controllers

import (
	"fmt"
	"strconv"

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

// ProcessController handles requests related to process management.
type ProcessController struct {
	ProcessService models.ProcessManagerService
}

// NewProcessController creates a new instance of ProcessController.
func NewProcessController(ps models.ProcessManagerService) *ProcessController {
	return &ProcessController{
		ProcessService: ps,
	}
}

// ShowProcessManager renders the process manager page.
// @Summary Show process manager
// @Description Displays a list of running processes.
// @Tags process
// @Produce html
// @Success 200 {string} html "Process manager page HTML"
// @Failure 500 {object} fiber.Map "Error message if processes cannot be fetched"
// @Router /processes [get]
func (pc *ProcessController) ShowProcessManager(c *fiber.Ctx) error {
	processes, err := pc.ProcessService.GetProcesses()
	if err != nil {
		// Log the error appropriately in a real application
		fmt.Println("Error fetching processes:", err)
		return c.Status(fiber.StatusInternalServerError).Render("pages/process_manager", fiber.Map{
			"Title":     "Process Manager",
			"Processes": []models.Process{}, // Empty list on error
			"Error":     "Failed to retrieve process list.",
		})
	}

	return c.Render("pages/process_manager", fiber.Map{
		"Title":     "Process Manager",
		"Processes": processes,
	})
}

// HandleKillProcess handles the request to kill a specific process.
// @Summary Kill a process
// @Description Terminates a process by its PID.
// @Tags process
// @Produce html
// @Param pid path int true "Process ID"
// @Success 302 "Redirects to process manager page"
// @Failure 400 {object} fiber.Map "Error message if PID is invalid"
// @Failure 500 {object} fiber.Map "Error message if process cannot be killed"
// @Router /processes/kill/{pid} [post]
func (pc *ProcessController) HandleKillProcess(c *fiber.Ctx) error {
	pidStr := c.Params("pid")
	pid, err := strconv.Atoi(pidStr)
	if err != nil {
		// Log error
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid PID format"})
	}

	err = pc.ProcessService.KillProcess(pid)
	if err != nil {
		// Log error
		// In a real app, you might want to return a more user-friendly error page or message
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to kill process"})
	}

	// Redirect back to the process manager page
	return c.Redirect("/processes")
}
