package response_test

import (
	"errors"
	"net/http"
	"testing"

	errs "gateway/internal/library/errors"
	"gateway/internal/library/errors/code"
	"gateway/internal/library/validate"
	"gateway/internal/response"
)

func TestWrapRequestError(t *testing.T) {
	t.Parallel()

	response.RequestErrScope = code.Facade

	e := response.WrapRequestError(errors.New("field id is required"))
	be := errs.FromError(e)
	if be == nil {
		t.Fatal("expected business error")
	}
	if be.Category() != code.InputInvalidFormat {
		t.Fatalf("category = %d, want %d", be.Category(), code.InputInvalidFormat)
	}
	if be.HTTPStatus() != http.StatusBadRequest {
		t.Fatalf("http = %d, want 400", be.HTTPStatus())
	}
}

func TestWrapRequestErrorValidationErrors(t *testing.T) {
	t.Parallel()

	response.RequestErrScope = code.Facade

	ve := validate.ValidationErrors{
		{Field: "email", Message: "email must be a valid email address"},
	}
	e := response.WrapRequestError(ve)
	be := errs.FromError(e)
	if be == nil {
		t.Fatal("expected business error")
	}
	if be.Category() != code.InputInvalidFormat {
		t.Fatalf("category = %d, want %d", be.Category(), code.InputInvalidFormat)
	}
	if be.HTTPStatus() != http.StatusBadRequest {
		t.Fatalf("http = %d, want 400", be.HTTPStatus())
	}
}

func TestWrapRequestErrorPreservesBusinessError(t *testing.T) {
	t.Parallel()

	orig := errs.For(code.Facade).ResNotFound("x")
	if wrapped := response.WrapRequestError(orig); !errors.Is(wrapped, orig) {
		t.Fatal("business error should not be wrapped")
	}
}
