package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gitea.maison43.duckdns.org/gilles/matosbox/internal/data/ent"
	"gitea.maison43.duckdns.org/gilles/matosbox/internal/data/ent/emplacement"
)

type emplacementRequest struct {
	Nom         *string `json:"nom"`
	ParentID    *string `json:"parent_id"`
	Slug        *string `json:"slug"`
	Piece       *string `json:"piece"`
	Meuble      *string `json:"meuble"`
	NumeroBoite *string `json:"numero_boite"`
	Icone       *string `json:"icone"`
}

// @Summary Lister les emplacements
// @Tags Emplacements
// @Produce json
// @Param page query int false "Page"
// @Param limit query int false "Limite"
// @Success 200 {object} map[string]any
// @Failure 500 {object} map[string]string
// @Router /emplacements [get]
func (h *Handler) ListEmplacements(c *gin.Context) {
	limit, offset, page := parsePagination(c.Query("page"), c.Query("limit"))
	query := h.client.Emplacement.Query()
	if nom := c.Query("nom"); nom != "" {
		query = query.Where(emplacement.NomContainsFold(nom))
	}
	total, err := query.Count(c.Request.Context())
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"erreur": "impossible de compter les emplacements"})
		return
	}

	items, err := query.
		Order(ent.Desc(emplacement.FieldCreatedAt)).
		Limit(limit).
		Offset(offset).
		All(c.Request.Context())
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"erreur": "impossible de lister les emplacements"})
		return
	}
	respondPaginated(c, items, total, page, limit)
}

// @Summary Creer un emplacement
// @Tags Emplacements
// @Accept json
// @Produce json
// @Param body body emplacementRequest true "Emplacement a creer"
// @Success 201 {object} ent.Emplacement
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /emplacements [post]
func (h *Handler) CreateEmplacement(c *gin.Context) {
	var req emplacementRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"erreur": "donnees invalides"})
		return
	}
	if req.Nom == nil || *req.Nom == "" {
		c.JSON(http.StatusBadRequest, gin.H{"erreur": "le champ nom est obligatoire"})
		return
	}

	create := h.client.Emplacement.Create().SetNom(*req.Nom)
	if req.ParentID != nil && *req.ParentID != "" {
		if parsed, err := uuid.Parse(*req.ParentID); err == nil {
			create.SetParentID(parsed)
		}
	}
	if req.Slug != nil {
		create.SetNillableSlug(req.Slug)
	}
	if req.Piece != nil {
		create.SetNillablePiece(req.Piece)
	}
	if req.Meuble != nil {
		create.SetNillableMeuble(req.Meuble)
	}
	if req.NumeroBoite != nil {
		create.SetNillableNumeroBoite(req.NumeroBoite)
	}
	if req.Icone != nil {
		create.SetNillableIcone(req.Icone)
	}

	created, err := create.Save(c.Request.Context())
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"erreur": "impossible de creer l'emplacement"})
		return
	}
	c.JSON(http.StatusCreated, created)
}

// @Summary Recuperer un emplacement
// @Tags Emplacements
// @Produce json
// @Param id path string true "ID emplacement"
// @Success 200 {object} ent.Emplacement
// @Failure 400 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /emplacements/{id} [get]
func (h *Handler) GetEmplacement(c *gin.Context) {
	id, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"erreur": "identifiant invalide"})
		return
	}

	item, err := h.client.Emplacement.Get(c.Request.Context(), id)
	if err != nil {
		if ent.IsNotFound(err) {
			c.JSON(http.StatusNotFound, gin.H{"erreur": "emplacement introuvable"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"erreur": "impossible de charger l'emplacement"})
		return
	}
	c.JSON(http.StatusOK, item)
}

// @Summary Mettre a jour un emplacement
// @Tags Emplacements
// @Accept json
// @Produce json
// @Param id path string true "ID emplacement"
// @Param body body emplacementRequest true "Emplacement a mettre a jour"
// @Success 200 {object} ent.Emplacement
// @Failure 400 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /emplacements/{id} [put]
func (h *Handler) UpdateEmplacement(c *gin.Context) {
	id, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"erreur": "identifiant invalide"})
		return
	}

	var req emplacementRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"erreur": "donnees invalides"})
		return
	}

	update := h.client.Emplacement.UpdateOneID(id)
	if req.Nom != nil {
		update.SetNom(*req.Nom)
	}
	if req.ParentID != nil {
		if *req.ParentID == "" {
			update.ClearParentID()
		} else if parsed, err := uuid.Parse(*req.ParentID); err == nil {
			update.SetParentID(parsed)
		}
	}
	if req.Slug != nil {
		update.SetNillableSlug(req.Slug)
	}
	if req.Piece != nil {
		update.SetNillablePiece(req.Piece)
	}
	if req.Meuble != nil {
		update.SetNillableMeuble(req.Meuble)
	}
	if req.NumeroBoite != nil {
		update.SetNillableNumeroBoite(req.NumeroBoite)
	}
	if req.Icone != nil {
		update.SetNillableIcone(req.Icone)
	}

	updated, err := update.Save(c.Request.Context())
	if err != nil {
		if ent.IsNotFound(err) {
			c.JSON(http.StatusNotFound, gin.H{"erreur": "emplacement introuvable"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"erreur": "impossible de mettre a jour l'emplacement"})
		return
	}
	c.JSON(http.StatusOK, updated)
}

// @Summary Supprimer un emplacement
// @Tags Emplacements
// @Param id path string true "ID emplacement"
// @Success 204 {string} string "No Content"
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /emplacements/{id} [delete]
func (h *Handler) DeleteEmplacement(c *gin.Context) {
	id, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"erreur": "identifiant invalide"})
		return
	}

	if err := h.client.Emplacement.DeleteOneID(id).Exec(c.Request.Context()); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"erreur": "impossible de supprimer l'emplacement"})
		return
	}
	c.Status(http.StatusNoContent)
}

// helper for compile reference
var _ = ent.IsNotFound
