package activity_log

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 ActivityLogHandlerInterface interface {
	Router()
}

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

func NewActivityLogHandler(helper helpers.HelperInterface, g *gin.RouterGroup) ActivityLogHandlerInterface {
	return &ActivityLogHandler{Helper: helper, Group: g}
}

func (h *ActivityLogHandler) Router() {
	r := h.Group
	{
		r.GET("/", h.GetAll)
		r.POST("/list", h.GetList)
		r.GET("/:id", h.GetByID)
		r.POST("/:id/revert", h.Revert)
	}
}

func (h *ActivityLogHandler) 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.ActivityLogFilterRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	u := usecases.NewActivityLogUsecase(h.Helper, *userid)
	logs, _, err := u.GetAll(req)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	response.Success(c, logs)
}

func (h *ActivityLogHandler) 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.NewActivityLogUsecase(h.Helper, *userid)
	res, err := u.GetList(req)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	response.Success(c, res)
}

func (h *ActivityLogHandler) 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.NewActivityLogUsecase(h.Helper, *userid)
	log, err := u.GetByID(id)
	if err != nil {
		response.Error(c, http.StatusNotFound, "activity log not found")
		return
	}

	response.Success(c, log)
}

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

	roleKey := ""
	if userid.UsersRole_Relation != nil {
		roleKey = userid.UsersRole_Relation.RoleKey
	}
	if roleKey != "SPM" {
		response.Error(c, http.StatusForbidden, "only Super Admin can revert")
		return
	}

	id := c.Param("id")
	u := usecases.NewActivityLogUsecase(h.Helper, *userid)
	if err := u.Revert(id); err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}

	response.Success(c, map[string]interface{}{"message": "action reverted successfully"})
}
