package middleware

import (
	"net/http"

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

// CORS handles Cross-Origin Resource Sharing (CORS) for the API
func CORS() gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.Request.Header.Get("Origin")

		// Debug logging
		logger := logrus.WithFields(logrus.Fields{
			"origin": origin,
			"path":   c.Request.URL.Path,
			"method": c.Request.Method,
		})
		logger.Debug("CORS request received")

		// For development, allow all origins
		// In production, you would want to restrict this
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", origin)
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
			c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, X-Requested-With")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type, Authorization")
		}

		// Handle preflight requests
		if c.Request.Method == http.MethodOptions {
			c.AbortWithStatus(http.StatusOK)
			return
		}

		c.Next()
	}
}
