package middleware

import (
	"baron-sso-backend/internal/response"
	"encoding/json"
	"strings"

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

// ErrorCodeEnricher injects machine-readable `code` into legacy error responses.
// This keeps backward compatibility (`error` stays) while migrating handlers
// incrementally to explicit code-based responses.
func ErrorCodeEnricher() fiber.Handler {
	return func(c *fiber.Ctx) error {
		err := c.Next()

		body := c.Response().Body()
		if len(body) == 0 {
			return err
		}

		contentType := string(c.Response().Header.ContentType())
		if contentType != "" && !strings.Contains(contentType, fiber.MIMEApplicationJSON) {
			return err
		}

		var payload map[string]any
		if unmarshalErr := json.Unmarshal(body, &payload); unmarshalErr != nil {
			return err
		}

		if _, hasError := payload["error"]; !hasError {
			return err
		}
		if _, hasCode := payload["code"]; hasCode {
			return err
		}

		payload["code"] = response.StatusCode(c.Response().StatusCode())
		updated, marshalErr := json.Marshal(payload)
		if marshalErr != nil {
			return err
		}

		c.Response().SetBodyRaw(updated)
		return err
	}
}
