package com.nursinghome.service;

import com.nursinghome.common.ApiException;
import com.nursinghome.entity.User;
import com.nursinghome.mapper.UserMapper;
import com.nursinghome.util.PasswordUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    private final UserMapper userMapper;

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    public User findById(Long id) {
        return userMapper.findById(id);
    }

    public List<User> listByRole(String role) {
        return userMapper.listByRole(role);
    }

    public User createUser(User user, boolean hashPassword) {
        if (userMapper.findByUsername(user.getUsername()) != null) {
            throw new ApiException("账号已存在");
        }
        if (hashPassword) {
            user.setPassword(PasswordUtil.hash(user.getPassword()));
        }
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        userMapper.insert(user);
        return user;
    }

    public void updateUser(User user) {
        userMapper.update(user);
    }

    public void updateStatus(Long id, Integer status) {
        userMapper.updateStatus(id, status);
    }

    public void updatePassword(Long id, String password) {
        userMapper.updatePassword(id, password);
    }
}
