package dev.service;

import dev.dao.UserDao;
import dev.model.User;
import dev.util.PasswordUtil;

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

    public boolean register(
            String username,
            String password,
            String email)
    {
        User existingUser = userDao.findByUsername(username);

        if (existingUser != null)
        {
            System.out.println("Username already exists.");
            return false;
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(PasswordUtil.hash(password));
        user.setEmail(email);

        return userDao.save(user);
    }

    public User login(
            String username,
            String password)
    {

        User user = userDao.findByUsername(username);

        if (user == null)
        {
            System.out.println("Invalid username.");
            return null;
        }

        if (!PasswordUtil.matches(password, user.getPassword()))
        {
            System.out.println("Invalid password.");
            return null;
        }

        return user;
    }
}