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

import (
	"net/http"
	"runtime/debug"
	"time"
)

func NewRecoveryMiddleware(print func(string, ...any)) MiddlewareFunc {
	mw := func(next Handler) Handler {
		return newRecoveryHandler(next, print)
	}
	return mw
}

type recoveryHandler struct {
	next  Handler
	print func(string, ...any)
}

func newRecoveryHandler(next Handler, print func(string, ...any)) *recoveryHandler {
	return &recoveryHandler{
		next:  next,
		print: print,
	}
}

func (hand recoveryHandler) ServeHTTP(rctx *Context) {
	exitFunc := func() {
		err := recover()
		if err != nil {
			rctx.Writer.WriteHeader(http.StatusInternalServerError)
			stack := string(debug.Stack())
			timestamp := time.Now().Format(time.RFC3339)
			hand.print("%s %v ; %s\n", timestamp, err, stack)
		}
	}
	defer exitFunc()
	hand.next.ServeHTTP(rctx)
}
