/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package router

func NewCorsMiddleware() MiddlewareFunc {
	mw := func(next Handler) Handler {
		return newCorsHandler(next)
	}
	return mw
}

type corsHandler struct {
	next Handler
}

func newCorsHandler(next Handler) *corsHandler {
	return &corsHandler{
		next: next,
	}
}

func (hand corsHandler) ServeHTTP(ctx *Context) {
	origin := ctx.Request.Header.Get("Origin")
	if origin != "" {
		ctx.SetHeader("Access-Control-Allow-Origin", origin)
		ctx.SetHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE, PATCH")
		ctx.SetHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
		ctx.SetHeader("Access-Control-Max-Age", "86400")
		ctx.SetHeader("Access-Control-Allow-Credentials", "true")
	}
	if ctx.Request.Method == "OPTIONS" {
		return
	}
	hand.next.ServeHTTP(ctx)
}
