package dev.service;

import dev.model.User;
import dev.dao.UserDao;
import org.mindrot.jbcrypt.BCrypt;

public class AuthService {
    private final UserDao userDao = new UserDao();
    public boolean register(String username, String password, String email) {

        // TODO:
        // Validate and register user
        if (username == null || username.isBlank() || password == null || password.isBlank()) {
            return false;
        }

        if (userDao.findByUsername(username) != null) {
            return false;
        }

        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
        User newUser = new User(username, hashedPassword, email);

        return userDao.save(newUser);
    }

    public User login(String username, String password) {

        // TODO:
        // Authenticate user
        User user = userDao.findByUsername(username);

        if (user == null) {
            return null;
        }

        if (BCrypt.checkpw(password, user.getPassword())) {
            return user;
        }

        return null;
    }

}