package dev.service;

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

public class AuthService
{
    private final UserDao userDao = new UserDao();

    public boolean register(String username, String password, String email)
    {


        if (username == null || username.isBlank()) return false;
        if (password == null || password.isBlank()) return false;

        if (email == null || email.isBlank()) return false;

        User existing = userDao.findByUsername(username.trim());
        if (existing != null) return false;

        String passwordHash = BCrypt.hashpw(password, BCrypt.gensalt(12));

        User user = new User();
        user.setUsername(username.trim());
        user.setPasswordHash(passwordHash);

        user.setEmail(email.trim());

        return userDao.save(user);

    }

    public User login(String username, String password)
    {

        if (username == null || username.isBlank()) return null;
        if (password == null || password.isBlank()) return null;

        User user = userDao.findByUsername(username.trim());
        if (user == null) return null;

        boolean ok = BCrypt.checkpw(password, user.getPasswordHash());
        return ok ? user : null;

    }

}