package projects

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"senlinai-agent/backend/internal/logic/auth"
)

type Handler struct {
	service *Service
}

func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

func (h *Handler) Register(router gin.IRouter) {
	router.POST("/projects", h.createProject)
	router.GET("/projects", h.listProjects)
	router.GET("/projects/:id/dashboard", h.dashboard)
	router.GET("/projects/:id/workspace", h.workspace)
}

func (h *Handler) createProject(c *gin.Context) {
	userID, ok := auth.CurrentUserID(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
		return
	}
	var input struct {
		Name        string `json:"name"`
		Description string `json:"description"`
	}
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
		return
	}
	project, err := h.service.CreateProject(userID, input.Name, input.Description)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusCreated, project)
}

func (h *Handler) listProjects(c *gin.Context) {
	userID, ok := auth.CurrentUserID(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
		return
	}
	projects, err := h.service.ListProjects(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list projects"})
		return
	}
	c.JSON(http.StatusOK, projects)
}

func (h *Handler) dashboard(c *gin.Context) {
	userID, ok := auth.CurrentUserID(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
		return
	}
	projectID, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project id"})
		return
	}
	dashboard, err := h.service.Dashboard(userID, uint(projectID))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load dashboard"})
		return
	}
	c.JSON(http.StatusOK, dashboard)
}

func (h *Handler) workspace(c *gin.Context) {
	userID, ok := auth.CurrentUserID(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
		return
	}
	projectID, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project id"})
		return
	}
	workspace, err := h.service.Workspace(userID, uint(projectID))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load workspace"})
		return
	}
	c.JSON(http.StatusOK, workspace)
}
