package service

import (
	"licserver/internal/model"
	"licserver/internal/utils"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestUserService_Register(t *testing.T) {
	db := utils.TestDB(t)
	config := utils.TestConfig()
	userService := NewUserService(db, config)

	// 测试正常注册
	err := userService.Register("testuser", "password123", "test@example.com", "123456")
	assert.NoError(t, err)

	var user model.User
	err = db.Where("username = ?", "testuser").First(&user).Error
	assert.NoError(t, err)
	assert.Equal(t, "testuser", user.Username)
	assert.Equal(t, "test@example.com", user.Email)
	assert.Equal(t, "user", user.Role)

	// 测试重复用户名
	err = userService.Register("testuser", "password123", "test2@example.com", "123456")
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "用户名已存在")

	// 测试重复邮箱
	err = userService.Register("testuser2", "password123", "test@example.com", "123456")
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "邮箱已被注册")
}

func TestUserService_Login(t *testing.T) {
	db := utils.TestDB(t)
	config := utils.TestConfig()
	userService := NewUserService(db, config)

	// 创建测试用户
	err := userService.Register("testuser", "password123", "test@example.com", "123456")
	assert.NoError(t, err)

	// 测试正确登录
	token, err := userService.Login("testuser", "password123")
	assert.NoError(t, err)
	assert.NotEmpty(t, token)

	// 测试错误密码
	_, err = userService.Login("testuser", "wrongpassword")
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "密码错误")

	// 测试不存在的用户
	_, err = userService.Login("nonexistent", "password123")
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "用户不存在")
}
