package com.lingyue.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lingyue.auth.entity.User;
import com.lingyue.auth.repository.UserRepository;
import com.lingyue.common.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 用户服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {
    
    private final UserRepository userRepository;
    
    /**
     * 根据ID获取用户
     */
    public User getUserById(String userId) {
        return userRepository.selectById(userId);
    }
    
    /**
     * 根据用户名获取用户
     */
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return userRepository.selectOne(wrapper);
    }
    
    /**
     * 根据邮箱获取用户
     */
    public User getUserByEmail(String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        return userRepository.selectOne(wrapper);
    }
    
    /**
     * 更新用户资料
     * 
     * @param userId 用户ID
     * @param username 新用户名（可选）
     * @param email 新邮箱（可选）
     * @param avatarUrl 新头像URL（可选）
     * @return 更新后的用户
     */
    @Transactional
    public User updateProfile(String userId, String username, String email, String avatarUrl) {
        User user = userRepository.selectById(userId);
        if (user == null) {
            throw new ServiceException("用户不存在", 404);
        }
        
        // 校验用户名唯一性
        if (StringUtils.hasText(username) && !username.equals(user.getUsername())) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUsername, username);
            if (userRepository.selectCount(wrapper) > 0) {
                throw new ServiceException("用户名已被使用", 422);
            }
            user.setUsername(username);
        }
        
        // 校验邮箱唯一性
        if (StringUtils.hasText(email) && !email.equals(user.getEmail())) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getEmail, email);
            if (userRepository.selectCount(wrapper) > 0) {
                throw new ServiceException("邮箱已被使用", 422);
            }
            user.setEmail(email);
        }
        
        // 更新头像
        if (avatarUrl != null) {
            user.setAvatarUrl(avatarUrl);
        }
        
        user.setUpdateTime(new Date());
        userRepository.updateById(user);
        
        log.info("用户资料更新成功: userId={}", userId);
        return user;
    }
    
    /**
     * 更新用户密码哈希
     * 
     * @param userId 用户ID
     * @param newPasswordHash 新密码哈希
     */
    @Transactional
    public void updatePasswordHash(String userId, String newPasswordHash) {
        User user = userRepository.selectById(userId);
        if (user == null) {
            throw new ServiceException("用户不存在", 404);
        }
        
        user.setPasswordHash(newPasswordHash);
        user.setUpdateTime(new Date());
        userRepository.updateById(user);
        
        log.info("用户密码更新成功: userId={}", userId);
    }
}

