package backend.service.impl;
import backend.dao.impl.UserDao;
import backend.model.enums.LoginStatus;
import backend.model.User;
import backend.utils.impl.*;

public class AuthService {
    private UserDao userDao = new UserDao();
    public LoginStatus login(User user) {
        User dbUser = userDao.findByUsername(user.getUsername());
        if(dbUser==null)
            return LoginStatus.USER_NOT_FOUND;
        if(dbUser.getUsername().equals(user.getUsername())&&dbUser.getPassword().equals(user.getPassword()))
            return LoginStatus.SUCCESS;
        else if (!dbUser.getUsername().equals(user.getUsername())) {
            return LoginStatus.USER_NOT_FOUND;
        }
        return LoginStatus.PASSWORD_ERROR;
    }

    public LoginStatus register(User user) {
        User dbAccount = userDao.findByUsername(user.getUsername());
        if(dbAccount!=null)
            return LoginStatus.REGISTER_FAILED;
        //点击注册按钮后的事件
        int row = userDao.addUser(user);
        if(row>0)
            return LoginStatus.REGISTER_SUCCESS;
        else
            return LoginStatus.REGISTER_FAILED;
    }


    public boolean hasPermission(int userId, String requiredRole) {
        UserDao userDao = new UserDao();
        User user = userDao.findById(userId);
        if (user != null) {
            return user.getRole().equals(requiredRole);
        }
        return false;
    }
}

