package repository

import (
	"context"
	"testing"

	"github.com/user-management-system/internal/domain"
)

func TestUserRoleRepository_DeleteByUserAndRole(t *testing.T) {
	db := setupTestDB(t)
	repo := NewUserRoleRepository(db)
	ctx := context.Background()

	// 创建用户和角色
	user := &domain.User{Username: "roleuser", Password: "hash", Status: domain.UserStatusActive}
	db.WithContext(ctx).Create(user)

	role := &domain.Role{Code: "test_role", Name: "测试角色", Status: domain.RoleStatusEnabled}
	db.WithContext(ctx).Create(role)

	// 创建用户角色关联
	repo.Create(ctx, &domain.UserRole{UserID: user.ID, RoleID: role.ID})

	// 删除特定用户-角色关联
	err := repo.DeleteByUserAndRole(ctx, user.ID, role.ID)
	if err != nil {
		t.Fatalf("DeleteByUserAndRole() error = %v", err)
	}

	// 验证已删除
	exists, _ := repo.Exists(ctx, user.ID, role.ID)
	if exists {
		t.Error("DeleteByUserAndRole should have removed the association")
	}
}

func TestUserRoleRepository_GetUserRolesAndPermissions(t *testing.T) {
	db := setupTestDB(t)
	repo := NewUserRoleRepository(db)
	ctx := context.Background()

	// 创建用户
	user := &domain.User{Username: "permuser", Password: "hash", Status: domain.UserStatusActive}
	db.WithContext(ctx).Create(user)

	// 创建权限
	perm1 := &domain.Permission{Code: "user:read", Name: "读取用户", Status: domain.PermissionStatusEnabled}
	perm2 := &domain.Permission{Code: "user:write", Name: "写入用户", Status: domain.PermissionStatusEnabled}
	db.WithContext(ctx).Create(perm1)
	db.WithContext(ctx).Create(perm2)

	// 创建角色并分配权限
	role := &domain.Role{Code: "editor", Name: "编辑者", Status: domain.RoleStatusEnabled}
	db.WithContext(ctx).Create(role)

	// 角色-权限关联
	rpRepo := NewRolePermissionRepository(db)
	rpRepo.Create(ctx, &domain.RolePermission{RoleID: role.ID, PermissionID: perm1.ID})
	rpRepo.Create(ctx, &domain.RolePermission{RoleID: role.ID, PermissionID: perm2.ID})

	// 用户-角色关联
	repo.Create(ctx, &domain.UserRole{UserID: user.ID, RoleID: role.ID})

	// 测试获取用户角色和权限
	roles, perms, err := repo.GetUserRolesAndPermissions(ctx, user.ID)
	if err != nil {
		t.Fatalf("GetUserRolesAndPermissions() error = %v", err)
	}

	if len(roles) != 1 {
		t.Errorf("len(roles) = %d, want 1", len(roles))
	}
	if roles[0].Code != "editor" {
		t.Errorf("roles[0].Code = %s, want editor", roles[0].Code)
	}

	if len(perms) != 2 {
		t.Errorf("len(perms) = %d, want 2", len(perms))
	}
}
