package common

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/mhaya/game/game_cluster/internal/code"
)

func NewResult(statusCode int32) *code.Result {
	result := &code.Result{
		Code:    statusCode,
		Message: code.GetMessage(statusCode),
	}

	return result
}

func NewResultWithDetailErr(statusCode int32, errMsg string) *code.Result {
	result := &code.Result{
		Code:    statusCode,
		Message: code.GetMessage(statusCode),
	}

	if errMsg != "" {
		result.Message += ": " + errMsg
	}

	return result
}

func PackOkResult(c *gin.Context, statusCode int32, data ...interface{}) {
	result := &code.Result{
		Code:    statusCode,
		Message: code.GetMessage(statusCode),
	}

	if len(data) > 0 {
		result.Data = data[0]
	}

	c.JSON(http.StatusOK, result)
}

func PackDetailErrResult(c *gin.Context, statusCode int32, errMsg string) {
	result := &code.Result{
		Code:    statusCode,
		Message: code.GetMessage(statusCode),
	}

	if errMsg != "" {
		result.Message += ": " + errMsg
	}

	c.JSON(http.StatusOK, result)
}

func PackUnauthorizedResult(c *gin.Context, statusCode int32, errMsg string) {
	result := &code.Result{
		Code:    statusCode,
		Message: code.GetMessage(statusCode),
	}

	if errMsg != "" {
		result.Message += ": " + errMsg
	}

	c.AbortWithStatusJSON(http.StatusUnauthorized, result)
}

func PackForbiddenResult(c *gin.Context, statusCode int32, errMsg string) {
	result := &code.Result{
		Code:    statusCode,
		Message: code.GetMessage(statusCode),
	}

	if errMsg != "" {
		result.Message += ": " + errMsg
	}

	c.AbortWithStatusJSON(http.StatusForbidden, result)
}
