package tipos_servicos

import (
	"net/http"
	"strings"

	"photum-backend/internal/db/generated"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type Handler struct {
	service *Service
}

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

type TipoServicoResponse struct {
	ID   string `json:"id"`
	Nome string `json:"nome"`
}

type CreateTipoServicoRequest struct {
	Nome string `json:"nome" binding:"required"`
}

func toResponse(t generated.TiposServico) TipoServicoResponse {
	return TipoServicoResponse{
		ID:   uuid.UUID(t.ID.Bytes).String(),
		Nome: t.Nome,
	}
}

// Create godoc
// @Summary      Create a new service type
// @Tags         tipos_servicos
// @Accept       json
// @Produce      json
// @Security     BearerAuth
// @Param        request body CreateTipoServicoRequest true "Nome"
// @Success      201  {object}  TipoServicoResponse
// @Failure      400  {object}  map[string]string
// @Failure      409  {object}  map[string]string
// @Router       /api/tipos-servicos [post]
func (h *Handler) Create(c *gin.Context) {
	var req CreateTipoServicoRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	regiao := c.GetString("regiao")
	tipo, err := h.service.Create(c.Request.Context(), req.Nome, regiao)
	if err != nil {
		if strings.Contains(err.Error(), "duplicate key value") {
			c.JSON(http.StatusConflict, gin.H{"error": "Tipo de Servico already exists"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, toResponse(*tipo))
}

// List godoc
// @Summary      List all service types
// @Tags         tipos_servicos
// @Accept       json
// @Produce      json
// @Security     BearerAuth
// @Success      200  {array}  TipoServicoResponse
// @Router       /api/tipos-servicos [get]
func (h *Handler) List(c *gin.Context) {
	regiao := c.GetString("regiao")
	tipos, err := h.service.List(c.Request.Context(), regiao)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	var response []TipoServicoResponse
	for _, tipo := range tipos {
		response = append(response, toResponse(tipo))
	}
	c.JSON(http.StatusOK, response)
}

// Update godoc
// @Summary      Update a service type
// @Tags         tipos_servicos
// @Accept       json
// @Produce      json
// @Security     BearerAuth
// @Param        id   path      string  true  "ID"
// @Param        request body CreateTipoServicoRequest true "Nome"
// @Success      200  {object}  TipoServicoResponse
// @Router       /api/tipos-servicos/{id} [put]
func (h *Handler) Update(c *gin.Context) {
	id := c.Param("id")
	var req CreateTipoServicoRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	regiao := c.GetString("regiao")
	tipo, err := h.service.Update(c.Request.Context(), id, req.Nome, regiao)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, toResponse(*tipo))
}

// Delete godoc
// @Summary      Delete a service type
// @Tags         tipos_servicos
// @Accept       json
// @Produce      json
// @Security     BearerAuth
// @Param        id   path      string  true  "ID"
// @Success      204  {object}  nil
// @Router       /api/tipos-servicos/{id} [delete]
func (h *Handler) Delete(c *gin.Context) {
	id := c.Param("id")
	regiao := c.GetString("regiao")
	if err := h.service.Delete(c.Request.Context(), id, regiao); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.Status(http.StatusNoContent)
}
