package service

import (
    "errors"
    "github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/model"
    "github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/database"
)

type UserService struct {
	userRepo *database.UserRepository
}

func NewUserService(userRepo *database.UserRepository) *UserService {
	return &UserService{userRepo: userRepo}
}

// 用户注册
func (s *UserService) Register(username, email, password string) (string, error) {
	// 检查用户是否已存在
	if _, err := s.userRepo.GetByEmail(email); err == nil {
		return "", errors.New("用户已存在")
	}
	
	// 创建新用户
	user := &model.User{
		Username: username,
		Email:    email,
		Password: password, // 实际应用中需要加密
	}
	
	userID, err := s.userRepo.Create(user)
	if err != nil {
		return "", err
	}
	
	return userID, nil
}

// 用户登录
func (s *UserService) Login(email, password string) (string, string, error) {
	user, err := s.userRepo.GetByEmail(email)
	if err != nil {
		return "", "", errors.New("用户不存在")
	}
	
	// 实际应用中需要验证密码
	if user.Password != password {
		return "", "", errors.New("密码错误")
	}
	
	// 生成 token (实际应用中应使用 JWT 等)
	token := "fake-token-" + user.ID
	
	return token, user.ID, nil
}

// 获取用户信息
func (s *UserService) GetProfile(userID string) (*model.User, error) {
	user, err := s.userRepo.GetByID(userID)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	
	return user, nil
}

// 更新用户信息
func (s *UserService) UpdateProfile(userID, username, avatar string) error {
	user, err := s.userRepo.GetByID(userID)
	if err != nil {
		return errors.New("用户不存在")
	}
	
	user.Username = username
	if avatar != "" {
		user.Avatar = avatar
	}
	
	return s.userRepo.Update(user)
}