package org

import (
	"bytes"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/store/identity"
)

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

	handler := &InviteHandler{organizationHandlerBase: organizationHandlerBase{organizations: routeOrganizationProvider{}}}
	router := gin.New()
	router.POST("/api/v1/orgs/:orgId/invites", func(ctx *gin.Context) {
		api.SetAuthenticatedUser(ctx, identity.AuthenticatedUser{User: identity.User{ID: "usr_1"}})
	}, handleOrgAuthJSON[dto.OrganizationInviteCreateRequest](handler.Create))

	recorder := httptest.NewRecorder()
	request := httptest.NewRequest(http.MethodPost, "/api/v1/orgs/org_1/invites", bytes.NewBufferString(`{"email":"not-an-email"}`))
	request.Header.Set("Content-Type", "application/json")
	router.ServeHTTP(recorder, request)

	require.Equal(t, http.StatusBadRequest, recorder.Code)
}
