package dev.service;

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

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class AuthService {

    private final UserDao userDao = new UserDao();


    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 error", e);
        }
    }

    public boolean register(String username, String password, String email) {
        if (username == null || username.isBlank() || password == null || password.isBlank()) {
            System.out.println("Username and password are required.");
            return false;
        }
        if (userDao.findByUsername(username) != null) {
            System.out.println("Username already taken.");
            return false;
        }
        User user = new User(username, hashPassword(password), email.isBlank() ? null : email);
        return userDao.save(user);
    }

    public User login(String username, String password) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            System.out.println("User not found.");
            return null;
        }
        if (!user.getPassword().equals(hashPassword(password))) {
            System.out.println("Incorrect password.");
            return null;
        }
        return user;
    }
}