package handler

import (
	"baron-sso-backend/internal/domain"
	"baron-sso-backend/internal/service"
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

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

// --- Mocks ---

type MockKratosAdmin struct {
	mock.Mock
}

func (m *MockKratosAdmin) ListIdentities(ctx context.Context) ([]service.KratosIdentity, error) {
	args := m.Called(ctx)
	return args.Get(0).([]service.KratosIdentity), args.Error(1)
}

func (m *MockKratosAdmin) FindIdentityIDByIdentifier(ctx context.Context, identifier string) (string, error) {
	args := m.Called(ctx, identifier)
	return args.String(0), args.Error(1)
}

func (m *MockKratosAdmin) GetIdentity(ctx context.Context, id string) (*service.KratosIdentity, error) {
	args := m.Called(ctx, id)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*service.KratosIdentity), args.Error(1)
}

func (m *MockKratosAdmin) UpdateIdentity(ctx context.Context, id string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
	args := m.Called(ctx, id, traits, state)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*service.KratosIdentity), args.Error(1)
}

func (m *MockKratosAdmin) UpdateIdentityPassword(ctx context.Context, id, pw string) error {
	return m.Called(ctx, id, pw).Error(0)
}

func (m *MockKratosAdmin) DeleteIdentity(ctx context.Context, id string) error {
	return m.Called(ctx, id).Error(0)
}

func (m *MockKratosAdmin) ListIdentitySessions(ctx context.Context, identityID string) ([]service.KratosSession, error) {
	args := m.Called(ctx, identityID)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).([]service.KratosSession), args.Error(1)
}

func (m *MockKratosAdmin) GetSession(ctx context.Context, sessionID string) (*service.KratosSession, error) {
	args := m.Called(ctx, sessionID)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*service.KratosSession), args.Error(1)
}

func (m *MockKratosAdmin) DeleteSession(ctx context.Context, sessionID string) error {
	return m.Called(ctx, sessionID).Error(0)
}

type MockOryProvider struct {
	mock.Mock
}

func (m *MockOryProvider) CreateUser(user *domain.BrokerUser, password string) (string, error) {
	args := m.Called(user, password)
	return args.String(0), args.Error(1)
}

func (m *MockOryProvider) UpdateUserPassword(loginID, newPassword string, r *http.Request) error {
	return m.Called(loginID, newPassword, r).Error(0)
}

func (m *MockOryProvider) GetPasswordPolicy() (*domain.PasswordPolicy, error) {
	args := m.Called()
	return args.Get(0).(*domain.PasswordPolicy), args.Error(1)
}

type fakeUserHandlerWorksmobileSyncer struct {
	upserts []domain.User
}

func (f *fakeUserHandlerWorksmobileSyncer) EnqueueTenantUpsertIfInScope(ctx context.Context, tenant domain.Tenant) error {
	return nil
}

func (f *fakeUserHandlerWorksmobileSyncer) EnqueueTenantDeleteIfInScope(ctx context.Context, tenant domain.Tenant) error {
	return nil
}

func (f *fakeUserHandlerWorksmobileSyncer) EnqueueUserUpsertIfInScope(ctx context.Context, user domain.User) error {
	f.upserts = append(f.upserts, user)
	return nil
}

func (f *fakeUserHandlerWorksmobileSyncer) EnqueueUserDeleteIfInScope(ctx context.Context, user domain.User) error {
	return nil
}

func TestSanitizeUserMetadataRemovesLegacyClassificationFlags(t *testing.T) {
	metadata := map[string]any{
		"hanmacFamily": true,
		"userType":     "hanmac",
		"employeeId":   "E001",
	}

	sanitized := sanitizeUserMetadata(metadata)

	assert.NotContains(t, sanitized, "hanmacFamily")
	assert.NotContains(t, sanitized, "userType")
	assert.Equal(t, "E001", sanitized["employeeId"])
	assert.Contains(t, metadata, "hanmacFamily")
	assert.Contains(t, metadata, "userType")
}

type MockTenantServiceForUser struct {
	mock.Mock
	service.TenantService
}

func (m *MockTenantServiceForUser) GetTenantBySlug(ctx context.Context, slug string) (*domain.Tenant, error) {
	args := m.Called(ctx, slug)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.Tenant), args.Error(1)
}

func (m *MockTenantServiceForUser) GetTenant(ctx context.Context, id string) (*domain.Tenant, error) {
	args := m.Called(ctx, id)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.Tenant), args.Error(1)
}

func (m *MockTenantServiceForUser) GetTenantByDomain(ctx context.Context, emailDomain string) (*domain.Tenant, error) {
	for _, call := range m.ExpectedCalls {
		if call.Method == "GetTenantByDomain" {
			args := m.Called(ctx, emailDomain)
			if args.Get(0) == nil {
				return nil, args.Error(1)
			}
			return args.Get(0).(*domain.Tenant), args.Error(1)
		}
	}
	return nil, nil
}

func (m *MockTenantServiceForUser) ListManageableTenants(ctx context.Context, userID string) ([]domain.Tenant, error) {
	args := m.Called(ctx, userID)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).([]domain.Tenant), args.Error(1)
}

func (m *MockTenantServiceForUser) ListTenants(ctx context.Context, limit, offset int, parentID string) ([]domain.Tenant, int64, error) {
	args := m.Called(ctx, limit, offset, parentID)
	if args.Get(0) == nil {
		return nil, args.Get(1).(int64), args.Error(2)
	}
	return args.Get(0).([]domain.Tenant), args.Get(1).(int64), args.Error(2)
}

func (m *MockTenantServiceForUser) ProvisionTenantByDomain(ctx context.Context, domainName string) (*domain.Tenant, error) {
	args := m.Called(ctx, domainName)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.Tenant), args.Error(1)
}

func (m *MockTenantServiceForUser) RegisterTenant(ctx context.Context, name, slug, tenantType, description string, domains []string, parentID *string, creatorID string) (*domain.Tenant, error) {
	args := m.Called(ctx, name, slug, tenantType, description, domains, parentID, creatorID)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.Tenant), args.Error(1)
}

// --- Tests ---

func TestUserHandler_ExportUsersCSV_UsesTenantSlugAliasAndOmitsRole(t *testing.T) {
	app := fiber.New()
	mockRepo := new(MockUserRepoForHandler)
	h := &UserHandler{UserRepo: mockRepo}

	app.Use(func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{
			Role: domain.RoleSuperAdmin,
		})
		return c.Next()
	})
	app.Get("/users/export", h.ExportUsersCSV)

	createdAt := time.Date(2026, 4, 29, 12, 0, 0, 0, time.UTC)
	tenantID := "tenant-uuid"
	mockRepo.On("List", mock.Anything, 0, 10000, "", "test-tenant").
		Return([]domain.User{
			{
				ID:         "u-1",
				Email:      "user@test.com",
				Name:       "Test User",
				Phone:      "010-1111-2222",
				Role:       domain.RoleSuperAdmin,
				Status:     "active",
				TenantID:   &tenantID,
				Tenant:     &domain.Tenant{ID: tenantID, Slug: "test-tenant"},
				Department: "Legacy Department",
				Grade:      "책임",
				Position:   "팀장",
				JobTitle:   "플랫폼 운영",
				CreatedAt:  createdAt,
			},
		}, int64(1), nil).Once()

	req := httptest.NewRequest("GET", "/users/export?tenantSlug=test-tenant&includeIds=true", nil)
	resp, err := app.Test(req)
	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	bodyBytes, _ := io.ReadAll(resp.Body)
	body := strings.TrimPrefix(string(bodyBytes), "\ufeff")
	assert.Contains(t, body, "user_id,Email,Name,Phone,Status,tenant_id,tenant_slug,Grade,Position,JobTitle,CreatedAt")
	assert.Contains(t, body, "u-1,user@test.com,Test User,010-1111-2222,active,tenant-uuid,test-tenant,책임,팀장")
	assert.NotContains(t, body, "Role")
	assert.NotContains(t, body, "Department")
	mockRepo.AssertExpectations(t)
}

func TestUserHandler_ExportUsersCSV_OmitsIDsAndUsesTenantSlug(t *testing.T) {
	app := fiber.New()
	mockRepo := new(MockUserRepoForHandler)
	h := &UserHandler{UserRepo: mockRepo}

	app.Use(func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{
			Role: domain.RoleSuperAdmin,
		})
		return c.Next()
	})
	app.Get("/users/export", h.ExportUsersCSV)

	createdAt := time.Date(2026, 4, 29, 12, 0, 0, 0, time.UTC)
	tenantID := "tenant-uuid"
	mockRepo.On("List", mock.Anything, 0, 10000, "", "").
		Return([]domain.User{
			{
				ID:        "user-uuid",
				Email:     "user@test.com",
				Name:      "Test User",
				Phone:     "010-1111-2222",
				Status:    "active",
				TenantID:  &tenantID,
				Tenant:    &domain.Tenant{ID: tenantID, Slug: "test-tenant"},
				Grade:     "책임",
				Position:  "팀장",
				JobTitle:  "플랫폼 운영",
				CreatedAt: createdAt,
			},
		}, int64(1), nil).Once()

	req := httptest.NewRequest("GET", "/users/export?includeIds=false", nil)
	resp, err := app.Test(req)
	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	bodyBytes, _ := io.ReadAll(resp.Body)
	body := strings.TrimPrefix(string(bodyBytes), "\ufeff")
	assert.Contains(t, body, "Email,Name,Phone,Status,tenant_slug,Grade,Position,JobTitle,CreatedAt")
	assert.Contains(t, body, "user@test.com,Test User,010-1111-2222,active,test-tenant,책임,팀장")
	assert.NotContains(t, body, "user-uuid")
	assert.NotContains(t, body, "tenant-uuid")
	assert.NotContains(t, body, "ID,")
	mockRepo.AssertExpectations(t)
}

func TestUserHandler_ExportUsersCSV_TenantAdminFiltersByTenantIDWithoutCompanyCode(t *testing.T) {
	app := fiber.New()
	mockRepo := new(MockUserRepoForHandler)
	h := &UserHandler{UserRepo: mockRepo}

	tenantID := "tenant-uuid"
	app.Use(func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{
			Role:     domain.RoleTenantAdmin,
			TenantID: &tenantID,
			ManageableTenants: []domain.Tenant{
				{ID: tenantID, Slug: "test-tenant"},
			},
		})
		return c.Next()
	})
	app.Get("/users/export", h.ExportUsersCSV)

	createdAt := time.Date(2026, 4, 29, 12, 0, 0, 0, time.UTC)
	otherTenantID := "other-tenant-uuid"
	mockRepo.On("List", mock.Anything, 0, 10000, "", "").
		Return([]domain.User{
			{
				ID:        "user-uuid",
				Email:     "user@test.com",
				Name:      "Test User",
				Phone:     "010-1111-2222",
				Status:    "active",
				TenantID:  &tenantID,
				Tenant:    &domain.Tenant{ID: tenantID, Slug: "test-tenant"},
				Grade:     "책임",
				Position:  "팀장",
				JobTitle:  "플랫폼 운영",
				CreatedAt: createdAt,
			},
			{
				ID:        "other-user",
				Email:     "other@test.com",
				Name:      "Other User",
				Status:    "active",
				TenantID:  &otherTenantID,
				Tenant:    &domain.Tenant{ID: otherTenantID, Slug: "other-tenant"},
				CreatedAt: createdAt,
			},
		}, int64(2), nil).Once()

	req := httptest.NewRequest("GET", "/users/export?includeIds=false", nil)
	resp, err := app.Test(req)
	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	bodyBytes, _ := io.ReadAll(resp.Body)
	body := strings.TrimPrefix(string(bodyBytes), "\ufeff")
	assert.Contains(t, body, "user@test.com,Test User,010-1111-2222,active,test-tenant")
	assert.NotContains(t, body, "other@test.com")
	mockRepo.AssertExpectations(t)
}

func TestUserHandler_BulkCreateUsers(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)

	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
	}

	app.Post("/users/bulk", h.BulkCreateUsers)

	t.Run("Success - 2 users", func(t *testing.T) {
		mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
			ID:   "t-123",
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
				},
			},
		}, nil).Once()

		mockTenant.On("GetTenant", mock.Anything, "t-123").Return(&domain.Tenant{
			ID:   "t-123",
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
				},
			},
		}, nil)

		mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
		mockOry.On("CreateUser", mock.Anything, mock.Anything).Return("u-1", nil).Twice()

		payload := map[string]interface{}{
			"users": []map[string]interface{}{
				{
					"email":      "user1@test.com",
					"name":       "User One",
					"tenantSlug": "test-tenant",
					"metadata":   map[string]interface{}{"emp_id": "E001"},
				},
				{
					"email":      "user2@test.com",
					"name":       "User Two",
					"tenantSlug": "test-tenant",
					"metadata":   map[string]interface{}{"emp_id": "E002"},
				},
			},
		}
		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 map[string]interface{}
		json.NewDecoder(resp.Body).Decode(&result)
		results := result["results"].([]interface{})
		assert.Len(t, results, 2)
		assert.True(t, results[0].(map[string]interface{})["success"].(bool))
		assert.True(t, results[1].(map[string]interface{})["success"].(bool))
	})

	t.Run("Fail - Tenant Not Found", func(t *testing.T) {
		mockTenant.On("GetTenantBySlug", mock.Anything, "wrong-tenant").Return(nil, errors.New("not found")).Once()
		mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)

		payload := map[string]interface{}{
			"users": []map[string]interface{}{
				{
					"email":      "fail@test.com",
					"name":       "Fail User",
					"tenantSlug": "wrong-tenant",
				},
			},
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

		resp, _ := app.Test(req)
		var result map[string]interface{}
		json.NewDecoder(resp.Body).Decode(&result)
		results := result["results"].([]interface{})

		assert.False(t, results[0].(map[string]interface{})["success"].(bool))
		assert.Contains(t, results[0].(map[string]interface{})["message"].(string), "tenant not found")
	})

	t.Run("Fail - Schema Validation (Required)", func(t *testing.T) {
		mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
			ID:   "t-123",
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
				},
			},
		}, nil).Once()

		mockTenant.On("GetTenant", mock.Anything, "t-123").Return(&domain.Tenant{
			ID:   "t-123",
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
				},
			},
		}, nil)

		payload := map[string]interface{}{
			"users": []map[string]interface{}{
				{
					"email":      "missing-meta@test.com",
					"name":       "No Meta",
					"tenantSlug": "test-tenant",
					"metadata":   map[string]interface{}{}, // emp_id missing
				},
			},
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

		resp, _ := app.Test(req)
		var result map[string]interface{}
		json.NewDecoder(resp.Body).Decode(&result)
		results := result["results"].([]interface{})

		assert.False(t, results[0].(map[string]interface{})["success"].(bool))
		assert.Contains(t, results[0].(map[string]interface{})["message"].(string), "field emp_id is required")
	})

	t.Run("Fail - Schema Validation (Regex)", func(t *testing.T) {
		mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
			ID:   "t-123",
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_id", "validation": "^E[0-9]{3}$"},
				},
			},
		}, nil).Once()

		payload := map[string]interface{}{
			"users": []map[string]interface{}{
				{
					"email":      "regex-fail@test.com",
					"name":       "Regex Fail",
					"tenantSlug": "test-tenant",
					"metadata":   map[string]interface{}{"emp_id": "abc"}, // Should start with E and 3 digits
				},
			},
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

		resp, _ := app.Test(req)
		var result map[string]interface{}
		json.NewDecoder(resp.Body).Decode(&result)
		results := result["results"].([]interface{})

		assert.False(t, results[0].(map[string]interface{})["success"].(bool))
		assert.Contains(t, results[0].(map[string]interface{})["message"].(string), "match validation pattern")
	})
}

func TestUserHandler_BulkCreateUsers_ResolvesAdditionalAppointment(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
	}
	app.Post("/users/bulk", h.BulkCreateUsers)

	mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
		ID:     "t-primary",
		Slug:   "test-tenant",
		Name:   "Primary Tenant",
		Config: domain.JSONMap{},
	}, nil).Once()
	mockTenant.On("GetTenant", mock.Anything, "t-primary").Return(&domain.Tenant{
		ID:     "t-primary",
		Slug:   "test-tenant",
		Name:   "Primary Tenant",
		Config: domain.JSONMap{},
	}, nil)
	mockTenant.On("GetTenantBySlug", mock.Anything, "second-tenant").Return(&domain.Tenant{
		ID:     "t-second",
		Slug:   "second-tenant",
		Name:   "Second Tenant",
		Config: domain.JSONMap{},
	}, nil).Once()
	mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
	mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
		appointments, ok := user.Attributes["additionalAppointments"].([]any)
		if !ok || len(appointments) != 1 {
			return false
		}
		appointment, ok := appointments[0].(map[string]any)
		if !ok {
			return false
		}
		metadata, _ := appointment["metadata"].(map[string]any)
		return appointment["tenantId"] == "t-second" &&
			appointment["tenantSlug"] == "second-tenant" &&
			appointment["tenantName"] == "Second Tenant" &&
			appointment["department"] == "센터" &&
			appointment["grade"] == "수석" &&
			appointment["jobTitle"] == "Architecture" &&
			metadata["employee_id"] == "EMP002"
	}), mock.Anything).Return("u-appointment", nil).Once()

	payload := map[string]interface{}{
		"users": []map[string]interface{}{
			{
				"email":      "dual@test.com",
				"name":       "Dual User",
				"tenantSlug": "test-tenant",
				"metadata":   map[string]interface{}{"employee_id": "EMP001"},
				"additionalAppointments": []map[string]interface{}{
					{
						"tenantSlug": "second-tenant",
						"department": "센터",
						"grade":      "수석",
						"jobTitle":   "Architecture",
						"metadata":   map[string]interface{}{"employee_id": "EMP002"},
					},
				},
			},
		},
	}
	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)
	mockTenant.AssertExpectations(t)
	mockOry.AssertExpectations(t)
}

func TestUserHandler_BulkCreateUsers_AppendsEmailDomainTenantAtLowestPriority(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
	}
	app.Post("/users/bulk", h.BulkCreateUsers)

	mockTenant.On("GetTenantBySlug", mock.Anything, "gpdtdc").Return(&domain.Tenant{
		ID:     "t-gpdtdc",
		Slug:   "gpdtdc",
		Name:   "GPDTDC",
		Config: domain.JSONMap{},
	}, nil).Once()
	mockTenant.On("GetTenant", mock.Anything, "t-gpdtdc").Return(&domain.Tenant{
		ID:     "t-gpdtdc",
		Slug:   "gpdtdc",
		Name:   "GPDTDC",
		Config: domain.JSONMap{},
	}, nil)
	mockTenant.On("GetTenantByDomain", mock.Anything, "samaneng.com").Return(&domain.Tenant{
		ID:     "t-saman",
		Slug:   "saman",
		Name:   "삼안",
		Status: domain.TenantStatusActive,
		Config: domain.JSONMap{},
	}, nil).Once()
	mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
	mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
		if user.Attributes["tenant_id"] != "t-gpdtdc" {
			return false
		}
		if _, hasCompanyCode := user.Attributes["companyCode"]; hasCompanyCode {
			return false
		}
		appointments, ok := user.Attributes["additionalAppointments"].([]any)
		if !ok || len(appointments) != 1 {
			return false
		}
		appointment, ok := appointments[0].(map[string]any)
		if !ok {
			return false
		}
		return appointment["tenantId"] == "t-saman" &&
			appointment["tenantSlug"] == "saman" &&
			appointment["tenantName"] == "삼안" &&
			appointment["assignmentSource"] == "email_domain" &&
			appointment["sourceDomain"] == "samaneng.com"
	}), mock.Anything).Return("u-domain-assigned", nil).Once()

	payload := map[string]interface{}{
		"users": []map[string]interface{}{
			{
				"email":      "user@samaneng.com",
				"name":       "Domain User",
				"tenantSlug": "gpdtdc",
			},
		},
	}
	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, http.StatusOK, resp.StatusCode)

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	results := result["results"].([]interface{})
	assert.True(t, results[0].(map[string]interface{})["success"].(bool))
	mockTenant.AssertExpectations(t)
	mockOry.AssertExpectations(t)
}

func TestUserHandler_BulkCreateUsers_UsesEmailDomainTenantAsPrimaryWhenExplicitTenantMissing(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
	}
	app.Post("/users/bulk", h.BulkCreateUsers)

	mockTenant.On("GetTenantByDomain", mock.Anything, "samaneng.com").Return(&domain.Tenant{
		ID:     "t-saman",
		Slug:   "saman",
		Name:   "삼안",
		Status: domain.TenantStatusActive,
		Config: domain.JSONMap{},
	}, nil).Once()
	mockTenant.On("GetTenant", mock.Anything, "t-saman").Return(&domain.Tenant{
		ID:     "t-saman",
		Slug:   "saman",
		Name:   "삼안",
		Status: domain.TenantStatusActive,
		Config: domain.JSONMap{},
	}, nil)
	mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
	mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
		_, hasCompanyCode := user.Attributes["companyCode"]
		return user.Attributes["tenant_id"] == "t-saman" &&
			!hasCompanyCode &&
			user.Attributes["additionalAppointments"] == nil
	}), mock.Anything).Return("u-domain-primary", nil).Once()

	payload := map[string]interface{}{
		"users": []map[string]interface{}{
			{
				"email": "user@samaneng.com",
				"name":  "Domain Primary User",
			},
		},
	}
	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, http.StatusOK, resp.StatusCode)

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	results := result["results"].([]interface{})
	assert.True(t, results[0].(map[string]interface{})["success"].(bool))
	mockTenant.AssertExpectations(t)
	mockOry.AssertExpectations(t)
}

func TestUserHandler_ListUsersReturnsServiceUnavailableWhenKratosFails(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockRepo := new(MockUserRepoForHandler)

	h := &UserHandler{
		KratosAdmin: mockKratos,
		UserRepo:    mockRepo,
	}

	app.Use(func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{
			Role: domain.RoleSuperAdmin,
		})
		return c.Next()
	})
	app.Get("/users", h.ListUsers)

	mockKratos.On("ListIdentities", mock.Anything).Return([]service.KratosIdentity{}, errors.New("kratos down")).Once()

	req := httptest.NewRequest("GET", "/users?limit=10&offset=0", nil)
	resp, err := app.Test(req)

	assert.NoError(t, err)
	assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
	mockRepo.AssertNotCalled(t, "List", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything)
	mockKratos.AssertExpectations(t)
}

func TestUserHandler_ListUsersReturnsNextCursorWhenMoreRowsExist(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	createdAt := time.Date(2026, 5, 13, 8, 0, 0, 0, time.UTC)

	h := &UserHandler{KratosAdmin: mockKratos}

	app.Use(func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{
			Role: domain.RoleSuperAdmin,
		})
		return c.Next()
	})
	app.Get("/users", h.ListUsers)

	mockKratos.On("ListIdentities", mock.Anything).Return([]service.KratosIdentity{
		{ID: "u-3", State: "active", CreatedAt: createdAt, Traits: map[string]interface{}{"email": "c@example.com", "name": "C"}},
		{ID: "u-2", State: "active", CreatedAt: createdAt.Add(-time.Minute), Traits: map[string]interface{}{"email": "b@example.com", "name": "B"}},
		{ID: "u-1", State: "active", CreatedAt: createdAt.Add(-2 * time.Minute), Traits: map[string]interface{}{"email": "a@example.com", "name": "A"}},
	}, nil).Once()

	req := httptest.NewRequest("GET", "/users?limit=2", nil)
	resp, err := app.Test(req)

	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)

	var res userListResponse
	require.NoError(t, json.NewDecoder(resp.Body).Decode(&res))
	require.Len(t, res.Items, 2)
	require.NotEmpty(t, res.NextCursor)
	require.Equal(t, int64(3), res.Total)
}

func TestUserHandler_BulkCreateUsers_HanmacEmailPolicy(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	mockRepo := new(MockUserRepoForHandler)

	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
		UserRepo:      mockRepo,
	}

	app.Post("/users/bulk", h.BulkCreateUsers)

	rootID := "hanmac-family-id"
	companyID := "hanmac-id"
	tenants := []domain.Tenant{
		{ID: rootID, Slug: "hanmac-family", Name: "한맥가족"},
		{ID: companyID, Slug: "hanmac", Name: "한맥기술", ParentID: &rootID},
		{ID: "external-id", Slug: "external", Name: "외부사"},
	}

	t.Run("domain only email receives suggested final email with next suffix", func(t *testing.T) {
		mockTenant.On("GetTenantBySlug", mock.Anything, "hanmac").Return(&domain.Tenant{
			ID:   companyID,
			Slug: "hanmac",
		}, nil).Once()
		mockTenant.On("GetTenant", mock.Anything, companyID).Return(&domain.Tenant{
			ID:   companyID,
			Slug: "hanmac",
		}, nil).Maybe()
		mockTenant.On("ListTenants", mock.Anything, 10000, 0, "").Return(tenants, int64(len(tenants)), nil).Once()
		mockRepo.On("FindByTenantIDs", mock.Anything, []string{rootID, companyID}).Return([]domain.User{
			{Email: "cyhan@hanmaceng.co.kr", CompanyCode: "hanmac", TenantID: &companyID},
			{Email: "cyhan1@samaneng.com", CompanyCode: "hanmac", TenantID: &companyID},
		}, nil).Once()
		mockRepo.On("FindByCompanyCodes", mock.Anything, []string{"hanmac-family", "hanmac"}).Return([]domain.User{}, nil).Once()
		mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil).Once()
		mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
			return user.Email == "cyhan2@hanmaceng.co.kr"
		}), mock.Anything).Return("u-hanmac", nil).Once()

		payload := map[string]interface{}{
			"users": []map[string]interface{}{
				{
					"email":      "@hanmaceng.co.kr",
					"name":       "한치영",
					"tenantSlug": "hanmac",
				},
			},
		}
		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, http.StatusOK, resp.StatusCode)

		var result map[string]interface{}
		json.NewDecoder(resp.Body).Decode(&result)
		results := result["results"].([]interface{})
		row := results[0].(map[string]interface{})
		assert.True(t, row["success"].(bool))
		assert.Equal(t, "cyhan2@hanmaceng.co.kr", row["email"])
		assert.Equal(t, "@hanmaceng.co.kr", row["originalEmail"])
		assert.Contains(t, row["warnings"].([]interface{}), "suggested")
	})

	t.Run("full email duplicate local part is blocking error", func(t *testing.T) {
		mockTenant.On("GetTenantBySlug", mock.Anything, "hanmac").Return(&domain.Tenant{
			ID:   companyID,
			Slug: "hanmac",
		}, nil).Once()
		mockTenant.On("GetTenant", mock.Anything, companyID).Return(&domain.Tenant{
			ID:   companyID,
			Slug: "hanmac",
		}, nil).Maybe()
		mockTenant.On("ListTenants", mock.Anything, 10000, 0, "").Return(tenants, int64(len(tenants)), nil).Once()
		mockRepo.On("FindByTenantIDs", mock.Anything, []string{rootID, companyID}).Return([]domain.User{
			{Email: "han@hanmaceng.co.kr", CompanyCode: "hanmac", TenantID: &companyID},
		}, nil).Once()
		mockRepo.On("FindByCompanyCodes", mock.Anything, []string{"hanmac-family", "hanmac"}).Return([]domain.User{}, nil).Once()
		mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil).Once()

		payload := map[string]interface{}{
			"users": []map[string]interface{}{
				{
					"email":      "han@samaneng.com",
					"name":       "한치영",
					"tenantSlug": "hanmac",
				},
			},
		}
		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, http.StatusOK, resp.StatusCode)

		var result map[string]interface{}
		json.NewDecoder(resp.Body).Decode(&result)
		results := result["results"].([]interface{})
		row := results[0].(map[string]interface{})
		assert.False(t, row["success"].(bool))
		assert.Equal(t, "blockingError", row["status"])
		assert.Contains(t, row["message"].(string), "한맥가족 내에서 이미 사용 중인 이메일 ID입니다.")
	})
}

func TestUserHandler_CreateUser_HanmacEmailPolicyBlocksDuplicateLocalPart(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	mockRepo := new(MockUserRepoForHandler)

	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
		UserRepo:      mockRepo,
	}

	app.Post("/users", h.CreateUser)

	rootID := "hanmac-family-id"
	companyID := "hanmac-id"
	tenants := []domain.Tenant{
		{ID: rootID, Slug: "hanmac-family", Name: "한맥가족"},
		{ID: companyID, Slug: "hanmac", Name: "한맥기술", ParentID: &rootID},
	}

	mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil).Once()
	mockTenant.On("GetTenantBySlug", mock.Anything, "hanmac").Return(&domain.Tenant{
		ID:   companyID,
		Slug: "hanmac",
	}, nil).Once()
	mockTenant.On("ListTenants", mock.Anything, 10000, 0, "").Return(tenants, int64(len(tenants)), nil).Once()
	mockRepo.On("FindByTenantIDs", mock.Anything, []string{rootID, companyID}).Return([]domain.User{
		{Email: "han@hanmaceng.co.kr", CompanyCode: "hanmac", TenantID: &companyID},
	}, nil).Once()
	mockRepo.On("FindByCompanyCodes", mock.Anything, []string{"hanmac-family", "hanmac"}).Return([]domain.User{}, nil).Once()

	payload := map[string]interface{}{
		"email":      "han@samaneng.com",
		"name":       "한치영",
		"tenantSlug": "hanmac",
	}
	body, _ := json.Marshal(payload)
	req := httptest.NewRequest("POST", "/users", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")

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

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	assert.Contains(t, result["error"].(string), "한맥가족 내에서 이미 사용 중인 이메일 ID입니다.")
	mockOry.AssertNotCalled(t, "CreateUser")
}

func TestUserHandler_BulkUpdateUsers(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockRepo := new(MockUserRepoForHandler)
	worksmobile := &fakeUserHandlerWorksmobileSyncer{}
	h := &UserHandler{KratosAdmin: mockKratos, UserRepo: mockRepo, Worksmobile: worksmobile}

	app.Put("/users/bulk", func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{Role: domain.RoleSuperAdmin})
		return h.BulkUpdateUsers(c)
	})

	t.Run("Success - Update Role and Status", func(t *testing.T) {
		mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
			ID: "u-1", Traits: map[string]interface{}{"email": "u1@test.com", "tenant_id": "tenant-1"}, State: "active",
		}, nil).Once()

		mockKratos.On("UpdateIdentity", mock.Anything, "u-1", mock.Anything, "inactive").Return(&service.KratosIdentity{
			ID: "u-1",
			Traits: map[string]interface{}{
				"email":     "u1@test.com",
				"name":      "Bulk User",
				"tenant_id": "tenant-1",
			},
			State: "inactive",
		}, nil).Once()

		status := "inactive"
		payload := map[string]interface{}{
			"userIds": []string{"u-1"},
			"status":  &status,
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("PUT", "/users/bulk", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

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

		var result map[string]interface{}
		json.NewDecoder(resp.Body).Decode(&result)
		results := result["results"].([]interface{})
		assert.True(t, results[0].(map[string]interface{})["success"].(bool))
		assert.Len(t, worksmobile.upserts, 1)
		assert.Equal(t, "u-1", worksmobile.upserts[0].ID)
		assert.Equal(t, domain.UserStatusPreboarding, worksmobile.upserts[0].Status)
	})

	t.Run("Fail - Super admin cannot assign tenant or RP admin roles", func(t *testing.T) {
		for _, role := range []string{domain.RoleTenantAdmin, domain.RoleRPAdmin} {
			payload := map[string]interface{}{
				"userIds": []string{"u-1"},
				"role":    role,
			}
			body, _ := json.Marshal(payload)
			req := httptest.NewRequest("PUT", "/users/bulk", bytes.NewReader(body))
			req.Header.Set("Content-Type", "application/json")

			resp, _ := app.Test(req)
			assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
		}
	})

	t.Run("Fail - Tenant admin cannot update role", func(t *testing.T) {
		app := fiber.New()
		h := &UserHandler{KratosAdmin: new(MockKratosAdmin)}
		app.Put("/users/bulk", func(c *fiber.Ctx) error {
			c.Locals("user_profile", &domain.UserProfileResponse{Role: domain.RoleTenantAdmin})
			return h.BulkUpdateUsers(c)
		})

		role := domain.RoleSuperAdmin
		payload := map[string]interface{}{
			"userIds": []string{"u-1"},
			"role":    &role,
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("PUT", "/users/bulk", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

		resp, _ := app.Test(req)
		assert.Equal(t, fiber.StatusForbidden, resp.StatusCode)
	})
}

func TestUserHandler_BulkDeleteUsers(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	h := &UserHandler{KratosAdmin: mockKratos}

	app.Delete("/users/bulk", func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{Role: domain.RoleSuperAdmin})
		return h.BulkDeleteUsers(c)
	})

	t.Run("Success - Delete multiple", func(t *testing.T) {
		mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{ID: "u-1"}, nil).Once()
		mockKratos.On("GetIdentity", mock.Anything, "u-2").Return(&service.KratosIdentity{ID: "u-2"}, nil).Once()

		mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
		mockKratos.On("DeleteIdentity", mock.Anything, "u-2").Return(nil).Once()

		payload := map[string]interface{}{
			"userIds": []string{"u-1", "u-2"},
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("DELETE", "/users/bulk", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

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

func TestUserHandler_DeleteUserDeletesLocalReadModel(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	userRepo := new(MockUserRepoForHandler)
	h := &UserHandler{KratosAdmin: mockKratos, UserRepo: userRepo}

	app.Delete("/users/:id", func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{ID: "admin-1", Role: domain.RoleSuperAdmin})
		return h.DeleteUser(c)
	})

	mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()

	req := httptest.NewRequest(http.MethodDelete, "/users/u-1", nil)
	resp, err := app.Test(req)
	assert.NoError(t, err)
	assert.Equal(t, http.StatusNoContent, resp.StatusCode)
	assert.Equal(t, []string{"u-1"}, userRepo.deletedIDs)
	mockKratos.AssertExpectations(t)
}

func TestUserHandler_UpdateUser_AdminOnlyField(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockTenant := new(MockTenantServiceForUser)

	h := &UserHandler{
		KratosAdmin:   mockKratos,
		TenantService: mockTenant,
	}

	app.Put("/users/:id", func(c *fiber.Ctx) error {
		// Mock requester as regular user
		c.Locals("user_profile", &domain.UserProfileResponse{Role: domain.RoleUser})
		return h.UpdateUser(c)
	})

	t.Run("Fail - Regular user updating admin_only field", func(t *testing.T) {
		tenantID := "t-123"
		mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
			ID:     "u-1",
			Traits: map[string]interface{}{"email": "user@test.com", "tenant_id": tenantID},
		}, nil)

		mockTenant.On("GetTenant", mock.Anything, tenantID).Return(&domain.Tenant{
			ID:   tenantID,
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "salary", "adminOnly": true},
				},
			},
		}, nil)

		payload := map[string]interface{}{
			"metadata": map[string]interface{}{"salary": 5000},
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("PUT", "/users/u-1", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

		resp, _ := app.Test(req)
		assert.Equal(t, 400, resp.StatusCode) // validation failed

		var result map[string]interface{}
		json.NewDecoder(resp.Body).Decode(&result)
		assert.Contains(t, result["error"].(string), "field salary is admin only")
	})
}

func TestUserHandler_UpdateUser_RejectsDeprecatedAdminRoles(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	h := &UserHandler{KratosAdmin: mockKratos}
	app.Put("/users/:id", func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{ID: "admin-1", Role: domain.RoleSuperAdmin})
		return h.UpdateUser(c)
	})

	for _, role := range []string{domain.RoleTenantAdmin, domain.RoleRPAdmin} {
		mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
			ID:     "u-1",
			Traits: map[string]interface{}{"email": "user@test.com", "role": domain.RoleUser},
			State:  "active",
		}, nil).Once()

		payload := map[string]interface{}{"role": role}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("PUT", "/users/u-1", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

		resp, _ := app.Test(req)
		assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
	}
	mockKratos.AssertExpectations(t)
}

func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
	t.Run("Success - Sync LoginID from namespaced metadata", func(t *testing.T) {
		app := fiber.New()
		mockKratos := new(MockKratosAdmin)
		mockTenant := new(MockTenantServiceForUser)
		h := &UserHandler{
			KratosAdmin:   mockKratos,
			TenantService: mockTenant,
		}
		app.Put("/users/:id", func(c *fiber.Ctx) error {
			c.Locals("user_profile", &domain.UserProfileResponse{Role: domain.RoleSuperAdmin})
			return h.UpdateUser(c)
		})

		tenantID := "t-123"
		userID := "u-1"
		mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
			ID: userID,
			Traits: map[string]interface{}{
				"email":       "user@test.com",
				"companyCode": "test-tenant",
				"tenant_id":   tenantID,
			},
		}, nil).Once()

		mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
			ID:   tenantID,
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
				},
			},
		}, nil)
		mockTenant.On("GetTenant", mock.Anything, tenantID).Return(&domain.Tenant{
			ID:   tenantID,
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
				},
			},
		}, nil)

		mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()

		// Expect traits to include 'custom_login_ids' synced from 'emp_no'
		mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
			ids, ok := traits["custom_login_ids"].([]string)
			return ok && len(ids) > 0 && ids[0] == "E1001"
		}), mock.Anything).Return(&service.KratosIdentity{
			ID: userID,
			Traits: map[string]interface{}{
				"custom_login_ids": []interface{}{"E1001"},
				"email":            "user@test.com",
			},
		}, nil).Once()

		payload := map[string]interface{}{
			"metadata": map[string]interface{}{
				tenantID: map[string]interface{}{
					"emp_no": "E1001",
				},
			},
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("PUT", "/users/"+userID, bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

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

	t.Run("Success - Sync LoginID from existing traits when not in metadata", func(t *testing.T) {
		app := fiber.New()
		mockKratos := new(MockKratosAdmin)
		mockTenant := new(MockTenantServiceForUser)
		h := &UserHandler{
			KratosAdmin:   mockKratos,
			TenantService: mockTenant,
		}
		app.Put("/users/:id", func(c *fiber.Ctx) error {
			c.Locals("user_profile", &domain.UserProfileResponse{Role: domain.RoleSuperAdmin})
			return h.UpdateUser(c)
		})

		tenantID := "t-123"
		userID := "u-2"
		mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
			ID: userID,
			Traits: map[string]interface{}{
				"email":       "user2@test.com",
				"companyCode": "test-tenant",
				"tenant_id":   tenantID,
				"id":          "old-id",
				tenantID: map[string]interface{}{
					"emp_no": "E2002",
				},
			},
		}, nil).Once()

		mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
			ID:   tenantID,
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_no", "isLoginId": true},
				},
			},
		}, nil)
		mockTenant.On("GetTenant", mock.Anything, tenantID).Return(&domain.Tenant{
			ID:   tenantID,
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_no", "isLoginId": true},
				},
			},
		}, nil)

		mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()

		// Even if metadata is empty, it should sync from existing traits
		mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
			ids, ok := traits["custom_login_ids"].([]string)
			return ok && len(ids) > 0 && ids[0] == "E2002"
		}), mock.Anything).Return(&service.KratosIdentity{
			ID: userID,
			Traits: map[string]interface{}{
				"custom_login_ids": []interface{}{"E2002"},
			},
		}, nil).Once()

		payload := map[string]interface{}{
			"name": "New Name",
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("PUT", "/users/"+userID, bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

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

func TestUserHandler_UpdateUser_PasswordUsesProvider(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
	}

	app.Put("/users/:id", func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{Role: domain.RoleSuperAdmin})
		return h.UpdateUser(c)
	})

	userID := "u-1"
	mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
		ID: userID,
		Traits: map[string]interface{}{
			"custom_login_ids": []interface{}{"dyddus1210"},
			"email":            "dyddus1210@gmail.com",
			"companyCode":      "test-tenant",
			"tenant_id":        "t-1",
			"emp_id":           "dyddus1210",
		},
	}, nil).Once()

	mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
		ID:   "t-1",
		Slug: "test-tenant",
		Config: domain.JSONMap{
			"userSchema": []interface{}{
				map[string]interface{}{"key": "emp_id", "isLoginId": true},
			},
		},
	}, nil)
	mockTenant.On("GetTenant", mock.Anything, "t-1").Return(&domain.Tenant{
		ID:   "t-1",
		Slug: "test-tenant",
		Config: domain.JSONMap{
			"userSchema": []interface{}{
				map[string]interface{}{"key": "emp_id", "isLoginId": true},
			},
		},
	}, nil)
	mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()

	mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
		ids, ok := traits["custom_login_ids"].([]string)
		return ok && len(ids) > 0 && ids[0] == "dyddus1210"
	}), "").Return(&service.KratosIdentity{
		ID: userID,
		Traits: map[string]interface{}{
			"custom_login_ids": []interface{}{"dyddus1210"},
			"email":            "dyddus1210@gmail.com",
		},
	}, nil).Once()

	mockOry.On("UpdateUserPassword", "dyddus1210", "asdfzxcv1234!", (*http.Request)(nil)).Return(nil).Once()

	payload := map[string]interface{}{
		"password": "asdfzxcv1234!",
	}
	body, _ := json.Marshal(payload)
	req := httptest.NewRequest("PUT", "/users/"+userID, bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")

	resp, _ := app.Test(req)
	assert.Equal(t, 200, resp.StatusCode)
	mockOry.AssertExpectations(t)
	mockKratos.AssertNotCalled(t, "UpdateIdentityPassword", mock.Anything, mock.Anything, mock.Anything)
}

func TestUserHandler_UpdateUser_PasswordFallsBackToEmail(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
	}

	app.Put("/users/:id", func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{Role: domain.RoleSuperAdmin})
		return h.UpdateUser(c)
	})

	userID := "u-2"
	mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
		ID: userID,
		Traits: map[string]interface{}{
			"email":       "dyddus1210@gmail.com",
			"companyCode": "test-tenant",
		},
	}, nil).Once()

	mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
		ID:   "t-1",
		Slug: "test-tenant",
	}, nil)
	mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()

	mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
		return traits["email"] == "dyddus1210@gmail.com"
	}), "").Return(&service.KratosIdentity{
		ID: userID,
		Traits: map[string]interface{}{
			"email": "dyddus1210@gmail.com",
		},
	}, nil).Once()

	mockOry.On("UpdateUserPassword", "dyddus1210@gmail.com", "asdfzxcv1234!", (*http.Request)(nil)).Return(nil).Once()

	payload := map[string]interface{}{
		"password": "asdfzxcv1234!",
	}
	body, _ := json.Marshal(payload)
	req := httptest.NewRequest("PUT", "/users/"+userID, bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")

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

func TestUserHandler_CreateUser_LoginIDSync(t *testing.T) {
	t.Run("Success - Sync LoginID from namespaced metadata", func(t *testing.T) {
		app := fiber.New()
		mockKratos := new(MockKratosAdmin)
		mockOry := new(MockOryProvider)
		mockTenant := new(MockTenantServiceForUser)
		h := &UserHandler{
			KratosAdmin:   mockKratos,
			OryProvider:   mockOry,
			TenantService: mockTenant,
		}
		app.Post("/users", h.CreateUser)

		tenantID := "t-123"
		mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
			ID:   tenantID,
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
				},
			},
		}, nil)
		mockTenant.On("GetTenant", mock.Anything, tenantID).Return(&domain.Tenant{
			ID:   tenantID,
			Slug: "test-tenant",
			Config: domain.JSONMap{
				"userSchema": []interface{}{
					map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
				},
			},
		}, nil)

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

		// Expect OryProvider.CreateUser to be called with attributes["custom_login_ids"] synced from metadata
		mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
			customIDs, ok := user.Attributes["custom_login_ids"].([]string)
			return ok && len(customIDs) > 0 && customIDs[0] == "E1001"
		}), mock.Anything).Return("u-1", nil).Once()

		// Mock GetIdentity after creation
		mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
			ID: "u-1",
			Traits: map[string]interface{}{
				"custom_login_ids": []interface{}{"E1001"},
				"email":            "new@test.com",
				"companyCode":      "test-tenant",
			},
		}, nil).Once()

		// Mock ListManageableTenants for mapIdentitySummary
		mockTenant.On("ListManageableTenants", mock.Anything, "u-1").Return([]domain.Tenant{}, nil).Once()

		payload := map[string]interface{}{
			"email":      "new@test.com",
			"name":       "New User",
			"tenantSlug": "test-tenant",
			"metadata": map[string]interface{}{
				tenantID: map[string]interface{}{
					"emp_no": "E1001",
				},
			},
		}
		body, _ := json.Marshal(payload)
		req := httptest.NewRequest("POST", "/users", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")

		resp, _ := app.Test(req)
		assert.Equal(t, 201, resp.StatusCode)
		mockOry.AssertExpectations(t)
	})
}

func TestUserHandler_CreateUser_UsesAdditionalAppointmentAsPrimaryTenant(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	mockRepo := new(MockUserRepoForHandler)
	worksmobile := &fakeUserHandlerWorksmobileSyncer{}
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
		UserRepo:      mockRepo,
		Worksmobile:   worksmobile,
	}
	app.Post("/users", h.CreateUser)

	tenantID := "33333333-3333-3333-3333-333333333333"
	mockTenant.On("GetTenant", mock.Anything, tenantID).Return(&domain.Tenant{
		ID:   tenantID,
		Slug: "saman",
	}, nil)
	mockTenant.On("GetTenantBySlug", mock.Anything, "saman").Return(&domain.Tenant{
		ID:   tenantID,
		Slug: "saman",
	}, nil)
	mockTenant.On("ListTenants", mock.Anything, 10000, 0, "").Return([]domain.Tenant{}, int64(0), nil)
	mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
	mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
		_, hasCompanyCode := user.Attributes["companyCode"]
		return user.Attributes["tenant_id"] == tenantID &&
			!hasCompanyCode &&
			user.Attributes["additionalAppointments"] != nil &&
			user.Attributes["userType"] == nil
	}), mock.Anything).Return("u-appointment", nil).Once()
	mockKratos.On("GetIdentity", mock.Anything, "u-appointment").Return(&service.KratosIdentity{
		ID: "u-appointment",
		Traits: map[string]interface{}{
			"email":       "new@samaneng.com",
			"name":        "Appointment User",
			"companyCode": "saman",
			"tenant_id":   tenantID,
			"additionalAppointments": []interface{}{
				map[string]interface{}{"tenantId": tenantID, "tenantSlug": "saman"},
			},
		},
		State: "active",
	}, nil).Once()

	payload := map[string]interface{}{
		"email": "new@samaneng.com",
		"name":  "Appointment User",
		"additionalAppointments": []map[string]interface{}{
			{"tenantId": tenantID, "tenantSlug": "saman", "tenantName": "삼안"},
		},
		"metadata": map[string]interface{}{
			"userType": "hanmac",
		},
	}
	body, _ := json.Marshal(payload)
	req := httptest.NewRequest("POST", "/users", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")

	resp, _ := app.Test(req)

	assert.Equal(t, 201, resp.StatusCode)
	assert.Len(t, worksmobile.upserts, 1)
	assert.Equal(t, tenantID, *worksmobile.upserts[0].TenantID)
	mockOry.AssertExpectations(t)
}

func TestUserHandler_CreateUser_AutoCreatesPersonalTenantWhenAssignmentMissing(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
	}
	app.Post("/users", h.CreateUser)

	personalTenantID := "01970f0d-9666-7548-963d-2890351f03dd"
	mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
	mockTenant.On(
		"RegisterTenant",
		mock.Anything,
		"Personal - personal-user@example.com",
		mock.MatchedBy(func(slug string) bool { return strings.HasPrefix(slug, "personal-") }),
		domain.TenantTypePersonal,
		"Automatically provisioned personal tenant",
		[]string(nil),
		(*string)(nil),
		"",
	).Return(&domain.Tenant{
		ID:     personalTenantID,
		Slug:   "personal-01970f0d96667548963d2890351f03dd",
		Name:   "Personal - personal-user@example.com",
		Type:   domain.TenantTypePersonal,
		Status: domain.TenantStatusActive,
		Config: domain.JSONMap{},
	}, nil).Once()
	mockTenant.On("GetTenant", mock.Anything, personalTenantID).Return(&domain.Tenant{
		ID:     personalTenantID,
		Slug:   "personal-01970f0d96667548963d2890351f03dd",
		Name:   "Personal - personal-user@example.com",
		Type:   domain.TenantTypePersonal,
		Status: domain.TenantStatusActive,
		Config: domain.JSONMap{},
	}, nil).Twice()
	mockTenant.On("GetTenantBySlug", mock.Anything, "personal-01970f0d96667548963d2890351f03dd").Return(&domain.Tenant{
		ID:     personalTenantID,
		Slug:   "personal-01970f0d96667548963d2890351f03dd",
		Name:   "Personal - personal-user@example.com",
		Type:   domain.TenantTypePersonal,
		Status: domain.TenantStatusActive,
		Config: domain.JSONMap{},
	}, nil).Maybe()
	mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
		_, hasCompanyCode := user.Attributes["companyCode"]
		return user.Email == "personal-user@example.com" &&
			user.Attributes["tenant_id"] == personalTenantID &&
			!hasCompanyCode
	}), mock.Anything).Return("u-personal", nil).Once()
	mockKratos.On("GetIdentity", mock.Anything, "u-personal").Return(&service.KratosIdentity{
		ID: "u-personal",
		Traits: map[string]interface{}{
			"email":       "personal-user@example.com",
			"name":        "Personal User",
			"companyCode": "personal-01970f0d96667548963d2890351f03dd",
			"tenant_id":   personalTenantID,
		},
		State: "active",
	}, nil).Once()
	payload := map[string]interface{}{
		"email": "personal-user@example.com",
		"name":  "Personal User",
	}
	body, _ := json.Marshal(payload)
	req := httptest.NewRequest("POST", "/users", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")

	resp, _ := app.Test(req)

	assert.Equal(t, http.StatusCreated, resp.StatusCode)
	mockTenant.AssertExpectations(t)
	mockOry.AssertExpectations(t)
	mockKratos.AssertExpectations(t)
}

func TestUserHandler_CreateUserAcceptsTenantSlugAndRejectsCompanyCode(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockOry := new(MockOryProvider)
	mockTenant := new(MockTenantServiceForUser)
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		OryProvider:   mockOry,
		TenantService: mockTenant,
	}
	app.Post("/users", h.CreateUser)

	mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil).Once()
	mockTenant.On("GetTenantBySlug", mock.Anything, "test-tenant").Return(&domain.Tenant{
		ID:   "tenant-id",
		Slug: "test-tenant",
	}, nil).Once()
	mockTenant.On("GetTenant", mock.Anything, "tenant-id").Return(&domain.Tenant{
		ID:     "tenant-id",
		Slug:   "test-tenant",
		Config: domain.JSONMap{},
	}, nil).Twice()
	mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
		_, hasCompanyCode := user.Attributes["companyCode"]
		return !hasCompanyCode && user.Attributes["tenant_id"] == "tenant-id"
	}), "Password1!").Return("user-id", nil).Once()
	mockKratos.On("GetIdentity", mock.Anything, "user-id").Return(&service.KratosIdentity{
		ID:    "user-id",
		State: "active",
		Traits: map[string]interface{}{
			"email":     "user@test.com",
			"name":      "Test User",
			"tenant_id": "tenant-id",
			"role":      domain.RoleUser,
		},
	}, nil).Once()

	body := `{"email":"user@test.com","password":"Password1!","name":"Test User","tenantSlug":"test-tenant"}`
	req := httptest.NewRequest(http.MethodPost, "/users", strings.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	resp, err := app.Test(req)

	require.NoError(t, err)
	require.Equal(t, http.StatusCreated, resp.StatusCode)
	mockTenant.AssertExpectations(t)
	mockOry.AssertExpectations(t)
	mockKratos.AssertExpectations(t)

	_, legacyErr := tenantSlugFromRequest("", "test-tenant")
	require.Error(t, legacyErr)
	require.Contains(t, legacyErr.Error(), "companyCode is deprecated")
}

func TestUserHandler_UpdateUserAcceptsTenantSlugAndRejectsCompanyCode(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockTenant := new(MockTenantServiceForUser)
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		TenantService: mockTenant,
	}
	app.Put("/users/:id", h.UpdateUser)

	identity := &service.KratosIdentity{
		ID:    "user-id",
		State: "active",
		Traits: map[string]interface{}{
			"email":     "user@test.com",
			"name":      "Test User",
			"tenant_id": "old-tenant-id",
			"role":      domain.RoleUser,
		},
	}
	mockKratos.On("GetIdentity", mock.Anything, "user-id").Return(identity, nil).Once()
	mockTenant.On("GetTenantBySlug", mock.Anything, "new-tenant").Return(&domain.Tenant{
		ID:   "new-tenant-id",
		Slug: "new-tenant",
	}, nil).Once()
	mockTenant.On("GetTenant", mock.Anything, "new-tenant-id").Return(&domain.Tenant{
		ID:     "new-tenant-id",
		Slug:   "new-tenant",
		Config: domain.JSONMap{},
	}, nil).Twice()
	mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]interface{}) bool {
		_, hasCompanyCode := traits["companyCode"]
		return !hasCompanyCode && traits["tenant_id"] == "new-tenant-id"
	}), "").Return(&service.KratosIdentity{
		ID:    "user-id",
		State: "active",
		Traits: map[string]interface{}{
			"email":     "user@test.com",
			"name":      "Test User",
			"tenant_id": "new-tenant-id",
			"role":      domain.RoleUser,
		},
	}, nil).Once()

	body := `{"tenantSlug":"new-tenant"}`
	req := httptest.NewRequest(http.MethodPut, "/users/user-id", strings.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	resp, err := app.Test(req)

	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)
	mockTenant.AssertExpectations(t)
	mockKratos.AssertExpectations(t)
}

func TestUserHandler_BulkUpdateUsersAcceptsTenantSlugAndRejectsCompanyCode(t *testing.T) {
	app := fiber.New()
	mockKratos := new(MockKratosAdmin)
	mockTenant := new(MockTenantServiceForUser)
	h := &UserHandler{
		KratosAdmin:   mockKratos,
		TenantService: mockTenant,
	}
	app.Use(func(c *fiber.Ctx) error {
		c.Locals("user_profile", &domain.UserProfileResponse{
			ID:   "admin-id",
			Role: domain.RoleSuperAdmin,
		})
		return c.Next()
	})
	app.Put("/users/bulk", h.BulkUpdateUsers)

	mockKratos.On("GetIdentity", mock.Anything, "user-id").Return(&service.KratosIdentity{
		ID:    "user-id",
		State: "active",
		Traits: map[string]interface{}{
			"email":     "user@test.com",
			"name":      "Test User",
			"tenant_id": "old-tenant-id",
			"role":      domain.RoleUser,
		},
	}, nil).Once()
	mockTenant.On("GetTenantBySlug", mock.Anything, "new-tenant").Return(&domain.Tenant{
		ID:   "new-tenant-id",
		Slug: "new-tenant",
	}, nil).Once()
	mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]interface{}) bool {
		_, hasCompanyCode := traits["companyCode"]
		return !hasCompanyCode && traits["tenant_id"] == "new-tenant-id"
	}), "active").Return(&service.KratosIdentity{
		ID:    "user-id",
		State: "active",
		Traits: map[string]interface{}{
			"email":     "user@test.com",
			"name":      "Test User",
			"tenant_id": "new-tenant-id",
			"role":      domain.RoleUser,
		},
	}, nil).Once()

	body := `{"userIds":["user-id"],"tenantSlug":"new-tenant"}`
	req := httptest.NewRequest(http.MethodPut, "/users/bulk", strings.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	resp, err := app.Test(req)

	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)
	mockTenant.AssertExpectations(t)
	mockKratos.AssertExpectations(t)

	legacyTenantSlug := "legacy-tenant"
	_, legacyErr := tenantSlugPointerFromRequest(nil, &legacyTenantSlug)
	require.Error(t, legacyErr)
	require.Contains(t, legacyErr.Error(), "companyCode is deprecated")
}

func TestUserHandler_MapToLocalUserKeepsRoleAndGradeSeparate(t *testing.T) {
	handler := &UserHandler{}
	identity := service.KratosIdentity{
		ID:    "user-grade-id",
		State: "active",
		Traits: map[string]interface{}{
			"email":       "grade@example.com",
			"name":        "Grade User",
			"role":        domain.RoleUser,
			"grade":       "수석",
			"position":    "팀장",
			"companyCode": "hanmac",
		},
	}

	localUser := handler.mapToLocalUser(identity)

	assert.Equal(t, domain.RoleUser, localUser.Role)
	assert.Equal(t, "수석", localUser.Grade)
	assert.Equal(t, "팀장", localUser.Position)
	assert.NotContains(t, localUser.Metadata, "grade")
}

func (m *MockKratosAdmin) CreateUser(ctx context.Context, user *domain.BrokerUser, password string) (string, error) {
	return "", nil
}

func (m *MockTenantServiceForUser) ListJoinedTenants(ctx context.Context, userID string) ([]domain.Tenant, error) {
	return nil, nil
}
