package dev.service;

import dev.model.User;
import dev.dao.UserDao;
import java.util.Base64;

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

    public boolean register(String username, String password, String email) {
        if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            System.out.println("Username and password are required.");
            return false;
        }

        User existing = userDao.findByUsername(username);
        if (existing != null) {
            System.out.println("Username already exists.");
            return false;
        }

        User user = new User(username, password, 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 or password.");
            return null;
        }

        String hashedInput = hashPassword(password);
        if (hashedInput.equals(user.getPassword())) {
            System.out.println("Login successful! Welcome, " + username);
            return user;
        } else {
            System.out.println("Invalid username or password.");
            return null;
        }
    }
    private String hashPassword(String password) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(password.getBytes(java.nio.charset.StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hash);
        } catch (java.security.NoSuchAlgorithmException e) {
            throw new RuntimeException("Hashing algorithm not found", e);
        }
    }

}