package middleware

import (
	"licserver/internal/utils"
	"net/http"

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

func ErrorHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		// 只处理第一个错误
		if len(c.Errors) > 0 {
			err := c.Errors[0].Err
			var statusCode int
			var response utils.ErrorResponse

			switch err {
			case utils.ErrUnauthorized:
				statusCode = http.StatusUnauthorized
				response = utils.ErrorResponse{
					Code:    401,
					Message: "未授权的访问",
					Detail:  err.Error(),
				}
			case utils.ErrForbidden:
				statusCode = http.StatusForbidden
				response = utils.ErrorResponse{
					Code:    403,
					Message: "禁止访问",
					Detail:  err.Error(),
				}
			case utils.ErrNotFound:
				statusCode = http.StatusNotFound
				response = utils.ErrorResponse{
					Code:    404,
					Message: "资源不存在",
					Detail:  err.Error(),
				}
			case utils.ErrInvalidInput:
				statusCode = http.StatusBadRequest
				response = utils.ErrorResponse{
					Code:    400,
					Message: "无效的输入",
					Detail:  err.Error(),
				}
			default:
				statusCode = http.StatusInternalServerError
				response = utils.ErrorResponse{
					Code:    500,
					Message: "服务器内部错误",
					Detail:  err.Error(),
				}
			}

			c.JSON(statusCode, response)
			c.Abort()
		}
	}
}
