package dev.service;

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

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class AuthService {

    private final UserDao userDao = new UserDao();

    public boolean register(String username, String password, String email) {
        if (userDao.findByUsername(username) != null) {
            return false;
        }

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

        return userDao.save(user);
    }

    public User login(String username, String password) {
        User user = userDao.findByUsername(username);

        if (user != null && user.getPassword().equals(hashPassword(password))) {
            return user;
        }

        return null;
    }

    private String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error hashing password", e);
        }
    }
}