package middleware

import (
	models "api-service/internal/models"
	"net/http"

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

// ErrorHandler handles errors globally
func ErrorHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		if len(c.Errors) > 0 {
			err := c.Errors.Last()
			status := http.StatusInternalServerError

			// Determine status code based on error type
			switch err.Type {
			case gin.ErrorTypeBind:
				status = http.StatusBadRequest
			case gin.ErrorTypeRender:
				status = http.StatusUnprocessableEntity
			case gin.ErrorTypePrivate:
				status = http.StatusInternalServerError
			}

			response := models.ErrorResponse{
				Error:   "internal_error",
				Message: err.Error(),
				Code:    status,
			}

			c.JSON(status, response)
		}
	}
}

// CORS middleware configuration
func CORSConfig() gin.HandlerFunc {
	return gin.HandlerFunc(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
		c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})
}
