// Package cors/wrapper/gin provides gin.HandlerFunc to handle CORS related
// requests as a wrapper of github.com/rs/cors handler.
package cors

import (
	"net/http"

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

// corsWrapper is a wrapper of cors.Cors handler which preserves information
// about configured 'optionPassthrough' option.
type corsWrapper struct {
	*Cors
	optionPassthrough bool
}

// build transforms wrapped cors.Cors handler into Gin middleware.
func (c corsWrapper) build() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		c.HandlerFunc(ctx.Writer, ctx.Request)
		if !c.optionPassthrough &&
			ctx.Request.Method == http.MethodOptions &&
			ctx.GetHeader("Access-Control-Request-Method") != "" {
			// Abort processing next Gin middlewares.
			ctx.AbortWithStatus(http.StatusOK)
		}
	}
}

// GinAllowAll creates a new CORS Gin middleware with permissive configuration
// allowing all origins with all standard methods with any header and
// credentials.
func GinAllowAll() gin.HandlerFunc {
	return corsWrapper{Cors: AllowAll()}.build()
}

// GinDefault creates a new CORS Gin middleware with default options.
func GinDefault() gin.HandlerFunc {
	return corsWrapper{Cors: Default()}.build()
}

// GinNew creates a new CORS Gin middleware with the provided options.
func GinNew(options Options) gin.HandlerFunc {
	return corsWrapper{New(options), options.OptionsPassthrough}.build()
}
