package httpx

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

	"github.com/stretchr/testify/require"

	"github.com/yan1h/agent-coding-workflow/internal/infra/errs"
)

func TestWriteJSON(t *testing.T) {
	rec := httptest.NewRecorder()
	WriteJSON(rec, 200, map[string]any{"x": 1})
	require.Equal(t, 200, rec.Code)
	require.Equal(t, "application/json; charset=utf-8", rec.Header().Get("Content-Type"))

	var body map[string]any
	require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
	require.EqualValues(t, 1, body["x"])
}

func TestWriteError_AppError(t *testing.T) {
	rec := httptest.NewRecorder()
	e := errs.New(errs.CodeInvalidInput, "bad").WithFields(map[string]any{"name": "required"})
	WriteError(rec, "req-1", e)
	require.Equal(t, 400, rec.Code)

	var body map[string]any
	require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
	require.Equal(t, "invalid_input", body["code"])
	require.Equal(t, "bad", body["message"])
	require.Equal(t, "req-1", body["request_id"])
	fields := body["fields"].(map[string]any)
	require.Equal(t, "required", fields["name"])
}

func TestWriteError_GenericError_BecomesInternal(t *testing.T) {
	rec := httptest.NewRecorder()
	WriteError(rec, "req-2", errors.New("boom"))
	require.Equal(t, 500, rec.Code)

	var body map[string]any
	require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
	require.Equal(t, "internal", body["code"])
	require.Equal(t, "internal server error", body["message"])
}
