package handler

import (
	"baron-sso-backend/internal/domain"
	"bytes"
	"encoding/json"
	"net/http/httptest"
	"testing"

	"github.com/gofiber/fiber/v2"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

func TestUserHandler_BulkCreateUsers_UUIDImportPolicy(t *testing.T) {
	tests := []struct {
		name  string
		field string
	}{
		{name: "id 필드 차단", field: "id"},
		{name: "uuid 필드 차단", field: "uuid"},
		{name: "userId 필드 차단", field: "userId"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			app := fiber.New()
			mockKratos := new(MockKratosAdmin)
			mockOry := new(MockOryProvider)

			h := &UserHandler{
				KratosAdmin: mockKratos,
				OryProvider: mockOry,
			}
			app.Post("/users/bulk", h.BulkCreateUsers)

			mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil).Once()

			payload := map[string]any{
				"users": []map[string]any{
					{
						"email":    "uuid-import@test.com",
						"name":     "UUID Import User",
						tt.field:   "550e8400-e29b-41d4-a716-446655440000",
						"metadata": map[string]any{},
					},
				},
			}
			body, _ := json.Marshal(payload)
			req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
			req.Header.Set("Content-Type", "application/json")

			resp, _ := app.Test(req)
			assert.Equal(t, 200, resp.StatusCode)

			var result struct {
				Results []bulkUserResult `json:"results"`
			}
			assert.NoError(t, json.NewDecoder(resp.Body).Decode(&result))
			assert.Len(t, result.Results, 1)
			assert.False(t, result.Results[0].Success)
			assert.Contains(t, result.Results[0].Message, "사용자 UUID 가져오기는 지원하지 않습니다")

			mockOry.AssertExpectations(t)
			mockKratos.AssertNotCalled(t, "FindIdentityIDByIdentifier", mock.Anything, mock.Anything)
		})
	}
}
