package handlers

import (
	"hamster-tycoon/storage/dao"
	"hamster-tycoon/storage/model"
	"hamster-tycoon/storage/validators"
	"hamster-tycoon/utils"
	"net/http"

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

func (hc *handlersContext) getAllHamsters(c *gin.Context) {
	cageID := c.Param("cageID")

	err := hc.validator.VarCtx(c, cageID, "uuid4")
	if err != nil {
		utils.JSONError(c.Writer, validators.NewDataValidationAPIError(err))
		return
	}

	hamsters, err := hc.db.GetAllHamsters(cageID)
	if err != nil {
		utils.GetLoggerFromCtx(c).WithError(err).Error("error while getting hamsters")
		utils.JSONErrorWithMessage(c.Writer, model.ErrInternalServer, "Error while getting hamsters")
		return
	}
	utils.JSON(c.Writer, http.StatusOK, hamsters)
}

func (hc *handlersContext) getAHamster(c *gin.Context) {
	cageID := c.Param("cageID")
	hamsterID := c.Param("hamsterID")

	err := hc.validator.VarCtx(c, cageID, "uuid4")
	if err != nil {
		utils.JSONError(c.Writer, validators.NewDataValidationAPIError(err))
		return
	}

	err = hc.validator.VarCtx(c, hamsterID, "uuid4")
	if err != nil {
		utils.JSONError(c.Writer, validators.NewDataValidationAPIError(err))
		return
	}

	hamster, err := hc.db.GetHamsterByID(hamsterID, cageID)
	if e, ok := err.(*dao.Error); ok {
		switch {
		case e.Type == dao.ErrTypeNotFound:
			utils.JSONErrorWithMessage(c.Writer, model.ErrNotFound, "Hamster not found")
			return
		default:
			utils.GetLoggerFromCtx(c).WithError(err).WithField("type", e.Type).Error("error GetHamster: get hamster error type not handled")
			utils.JSONError(c.Writer, model.ErrInternalServer)
			return
		}
	} else if err != nil {
		utils.GetLoggerFromCtx(c).WithError(err).Error("error while get hamster")
		utils.JSONError(c.Writer, model.ErrInternalServer)
		return
	}

	if hamster == nil {
		utils.JSONErrorWithMessage(c.Writer, model.ErrNotFound, "Hamster not found")
		return
	}

	utils.JSON(c.Writer, http.StatusOK, hamster)
}
