package dev.service;

import dev.model.User;
import dev.dao.UserDao;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

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

    public boolean register(String username, String password, String email) {
        if (userDao.findByUsername(username) != null) {
            System.out.println("Username already exists.");
            return false;
        }
        String hashed = hashPassword(password);
        User user = new User(username, hashed, 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());
            StringBuilder sb = new StringBuilder();
            for (byte b : hash) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Hashing failed", e);
        }
    }

}