package main

import (
	"baron-sso-backend/internal/response"
	"errors"
	"log/slog"

	"github.com/gofiber/fiber/v2"
)

func newErrorHandler(appEnv string) fiber.ErrorHandler {
	return func(c *fiber.Ctx, err error) error {
		code := fiber.StatusInternalServerError

		var e *fiber.Error
		if errors.As(err, &e) {
			code = e.Code
		}

		if appEnv == "production" || appEnv == "stage" {
			if code >= 500 {
				slog.Error("Internal Server Error",
					"error", err.Error(),
					"path", c.Path(),
					"method", c.Method(),
				)
				return response.Error(c, code, response.StatusCode(code), "Internal Server Error")
			}
		}

		return response.Error(c, code, response.StatusCode(code), err.Error())
	}
}
