package cost_component

import (
	"cargo-erp-backend/internal/handlers/dto"
	"cargo-erp-backend/internal/usecases"
	"cargo-erp-backend/pkg/helpers"
	"cargo-erp-backend/pkg/response"
	"net/http"

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

type CostComponentHandlerInterface interface {
	Router()
}

type CostComponentHandler struct {
	Helper helpers.HelperInterface
	Group  *gin.RouterGroup
}

func NewCostComponentHandler(helper helpers.HelperInterface, g *gin.RouterGroup) CostComponentHandlerInterface {
	return &CostComponentHandler{Helper: helper, Group: g}
}

func (h *CostComponentHandler) Router() {
	r := h.Group.Group("cost-components")
	{
		r.GET("/", h.GetAll)
		r.POST("/list", h.GetList)
		r.GET("/:id", h.GetByID)
		r.POST("/", h.Create)
		r.PUT("/:id", h.Update)
		r.DELETE("/:id", h.Delete)
		r.POST("/sortup", h.SortUp)
		r.POST("/sortdown", h.SortDown)
	}
}

func (h *CostComponentHandler) GetAll(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	var req dto.CostComponentFilterAllRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	u := usecases.NewCostComponentUsecase(h.Helper, *userid)
	components, _, err := u.GetAll(req)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	var responseDTO = make([]dto.CreateCostComponentResponse, 0)
	for _, v := range components {
		var DTO dto.CreateCostComponentResponse
		h.Helper.MapStructToStruct(v, "json", &DTO, "json")
		responseDTO = append(responseDTO, DTO)
	}
	response.Success(c, responseDTO)
}

func (h *CostComponentHandler) GetList(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}

	var req dto.DataTableRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "Request Format request invalid")
		return
	}
	u := usecases.NewCostComponentUsecase(h.Helper, *userid)
	res, err := u.GetList(req)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	response.Success(c, res)
	return
}

func (h *CostComponentHandler) GetByID(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	id := c.Param("id")

	u := usecases.NewCostComponentUsecase(h.Helper, *userid)
	component, err := u.GetByID(id)
	if err != nil {
		response.Error(c, http.StatusNotFound, "cost component not found")
		return
	}

	response.Success(c, component)
}

func (h *CostComponentHandler) Create(c *gin.Context) {
	var req dto.CreateCostComponentRequest
	if err := c.BindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	var merchantid *string = nil
	if userid.UsersRole_Relation == nil || userid.UsersRole_Relation.RoleKey != "SPM" {
		merchantid = userid.MerchantID
	}
	createdBy := userid.ID

	u := usecases.NewCostComponentUsecase(h.Helper, *userid)
	component, err := u.Create(req.Name, req.Code, req.Value, req.ComponentType, req.UnitType, createdBy, merchantid)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	var responseDTO dto.CreateCostComponentResponse
	h.Helper.MapStructToStruct(component, "json", &responseDTO, "json")
	response.Created(c, responseDTO)
}

func (h *CostComponentHandler) Update(c *gin.Context) {
	id := c.Param("id")

	var req dto.UpdateCostComponentRequest
	if err := c.BindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	updatedBy := userid.ID

	u := usecases.NewCostComponentUsecase(h.Helper, *userid)
	component, err := u.Update(id, req.Name, req.Code, req.Value, req.ComponentType, req.UnitType, updatedBy)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	var responseDTO dto.CreateCostComponentResponse
	h.Helper.MapStructToStruct(component, "json", &responseDTO, "json")
	response.Success(c, responseDTO)
}

func (h *CostComponentHandler) Delete(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	id := c.Param("id")
	u := usecases.NewCostComponentUsecase(h.Helper, *userid)
	if err := u.Delete(id); err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}

	response.Success(c, map[string]interface{}{"message": "cost component deleted"})
}

func (h *CostComponentHandler) SortUp(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	var req dto.MatchCostComponentRequest
	if err := c.BindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	sortUp := usecases.NewCostComponentUsecase(h.Helper, *userid)

	if err := sortUp.SortUp(req.ID); err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	response.Success(c, map[string]interface{}{"message": "Sorting Up Success"})
}

func (h *CostComponentHandler) SortDown(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	var req dto.MatchCostComponentRequest
	if err := c.BindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	sortUp := usecases.NewCostComponentUsecase(h.Helper, *userid)

	if err := sortUp.SortDown(req.ID); err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	response.Success(c, map[string]interface{}{"message": "Sorting Down Success"})
}
