package response

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

	"apps/backend/internal/domain"

	"github.com/stretchr/testify/require"
)

func TestOK_Envelope102000(t *testing.T) {
	rr := httptest.NewRecorder()
	Write(context.Background(), rr, map[string]string{"status": "ok"}, nil)
	require.Equal(t, http.StatusOK, rr.Code)
	var env Envelope
	require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &env))
	require.Equal(t, domain.SuccessCode, env.Code)
	require.Equal(t, int64(102000), env.Code)
	require.NotEmpty(t, env.Message)
	require.Nil(t, env.Error)
}

func TestFail_NotSuccessCode(t *testing.T) {
	rr := httptest.NewRecorder()
	Fail(rr, http.StatusBadRequest, 400001, "bad request", nil)
	var env Envelope
	require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &env))
	require.NotEqual(t, domain.SuccessCode, env.Code)
}

func TestNotImplemented_NotEmptySuccess(t *testing.T) {
	rr := httptest.NewRecorder()
	NotImplemented(rr, "auth.register")
	require.Equal(t, http.StatusNotImplemented, rr.Code)
	var env Envelope
	require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &env))
	require.False(t, IsSuccessCode(env.Code))
}

func TestWrite_Error(t *testing.T) {
	rr := httptest.NewRecorder()
	Write(context.Background(), rr, nil, Biz(http.StatusBadRequest, 400010, "x"))
	var env Envelope
	require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &env))
	require.Equal(t, int64(400010), env.Code)
}

func TestWrite_InternalErrorDoesNotLeakDetails(t *testing.T) {
	rr := httptest.NewRecorder()
	Write(context.Background(), rr, nil, errors.New("mongodb password=secret"))
	require.Equal(t, http.StatusInternalServerError, rr.Code)
	var env Envelope
	require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &env))
	require.Equal(t, "internal server error", env.Message)
	require.NotContains(t, rr.Body.String(), "secret")
}
