package test05.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import test05.mapper.UserMapper;
import test05.pojo.Result;
import test05.pojo.User;
import test05.service.UserService;
import test05.utils.JwtUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private UserMapper userMapper;
    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public Result login(User user) {
        User selectUser = userMapper.selectUserByName(user.getName());
        if (selectUser == null) {
            return Result.error("user dose not exist");
        }
        if (selectUser.getPassword().equals(user.getPassword())) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", selectUser.getId());
            map.put("name", selectUser.getName());
            return Result.success(JwtUtils.getJwt(map));
        }else{
            return Result.error("password incorrect");
        }
    }

    @Override
    public Result addUser(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectUserByName(user.getName());
        if (existingUser != null) {
            return Result.error("username already exists");
        }
        
        // 插入新用户
        int result = userMapper.insertUser(user);
        if (result > 0) {
            return Result.success("user created successfully");
        } else {
            return Result.error("failed to create user");
        }
    }
}
