package middleware

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

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

func decodeBody(t *testing.T, resp *http.Response) map[string]any {
	t.Helper()

	var body map[string]any
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		t.Fatalf("failed to decode body: %v", err)
	}
	return body
}

func TestErrorCodeEnricher_AddsCodeToLegacyErrorResponse(t *testing.T) {
	app := fiber.New()
	app.Use(ErrorCodeEnricher())
	app.Get("/legacy", func(c *fiber.Ctx) error {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
			"error": "missing token",
		})
	})

	req := httptest.NewRequest(http.MethodGet, "/legacy", nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("request failed: %v", err)
	}

	if resp.StatusCode != fiber.StatusUnauthorized {
		t.Fatalf("unexpected status code: %d", resp.StatusCode)
	}

	body := decodeBody(t, resp)
	if body["error"] != "missing token" {
		t.Fatalf("unexpected error field: %v", body["error"])
	}
	if body["code"] != "invalid_session" {
		t.Fatalf("unexpected code: %v", body["code"])
	}
}

func TestErrorCodeEnricher_DoesNotOverrideExistingCode(t *testing.T) {
	app := fiber.New()
	app.Use(ErrorCodeEnricher())
	app.Get("/already", func(c *fiber.Ctx) error {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"error": "invalid request",
			"code":  "validation_format",
		})
	})

	req := httptest.NewRequest(http.MethodGet, "/already", nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("request failed: %v", err)
	}

	body := decodeBody(t, resp)
	if body["code"] != "validation_format" {
		t.Fatalf("code should not be overridden: %v", body["code"])
	}
}

func TestErrorCodeEnricher_IgnoreSuccessPayload(t *testing.T) {
	app := fiber.New()
	app.Use(ErrorCodeEnricher())
	app.Get("/ok", func(c *fiber.Ctx) error {
		return c.JSON(fiber.Map{
			"message": "ok",
		})
	})

	req := httptest.NewRequest(http.MethodGet, "/ok", nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("request failed: %v", err)
	}

	body := decodeBody(t, resp)
	if _, found := body["code"]; found {
		t.Fatalf("code should not be injected for success payload")
	}
}
