package handlers

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/niangaodev/art-code/models"
	"github.com/niangaodev/art-code/repositories"
	"github.com/niangaodev/art-code/utils"
)

func GetCodeTypes(c *gin.Context) {
	list, err := repositories.GetCodeTypes()
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	utils.Success(c, repositories.BuildCodeTypesResponse(list))
}

func AdminGetCodeTypes(c *gin.Context) {
	GetCodeTypes(c)
}

func AdminCreateCodeType(c *gin.Context) {
	var ct models.CodeType
	if err := c.ShouldBindJSON(&ct); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}
	if ct.Name == "" {
		utils.Error(c, 400, "Name is required")
		return
	}
	if err := repositories.CreateCodeType(&ct); err != nil {
		utils.ServerError(c, err)
		return
	}
	utils.SuccessWithMsg(c, "Code type created", repositories.BuildCodeTypeResponse(&ct))
}

func AdminUpdateCodeType(c *gin.Context) {
	idStr := c.Param("id")
	var id uint
	if _, err := fmt.Sscanf(idStr, "%d", &id); err != nil {
		utils.Error(c, 400, "Invalid ID")
		return
	}
	var ct models.CodeType
	if err := c.ShouldBindJSON(&ct); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}
	ct.ID = id
	if err := repositories.UpdateCodeType(&ct); err != nil {
		utils.ServerError(c, err)
		return
	}
	utils.SuccessWithMsg(c, "Code type updated", nil)
}

func AdminDeleteCodeType(c *gin.Context) {
	idStr := c.Param("id")
	var id uint
	if _, err := fmt.Sscanf(idStr, "%d", &id); err != nil {
		utils.Error(c, 400, "Invalid ID")
		return
	}
	count, err := repositories.CountSnippetsByCodeTypeID(id)
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if count > 0 {
		utils.Error(c, 400, "Cannot delete: snippets are using this code type")
		return
	}
	if err := repositories.DeleteCodeType(id); err != nil {
		utils.ServerError(c, err)
		return
	}
	utils.SuccessWithMsg(c, "Code type deleted", nil)
}
