package middleware

import (
	"context"
	"fmt"

	"github.com/UpmeshLTD/urus-aio/infrastructure/logging"
	"github.com/UpmeshLTD/urus-aio/infrastructure/server/endpoint"
)

// PanicRecovery is a middleware that protects and endpoint from crashing the system when panicking.
func PanicRecovery() endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return endpoint.EndpointFunc(func(ctx context.Context, request interface{}) (response interface{}, err error) {
			defer func() {
				if r := recover(); r != nil {
					response = nil
					err = fmt.Errorf("panic error: %v", r)

					logger := logging.FromContext(ctx)
					logger.Errorw("panic error", "data", r)
				}
			}()

			return next.Invoke(ctx, request)
		})
	}
}
