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();

    public boolean register(String username, String password, String email) {

        // TODO:
        // Validate and register user

        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 exists.");
            return false;
        }

        User user = new User(0, username, hashPassword(password), email);

        return userDao.save(user);
    }

    public User login(String username, String password) {

        // TODO:
        // Authenticate user

        User user = userDao.findByUsername(username);

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

        if (!user.getPassword().equals(hashPassword(password))) {
            System.out.println("Invalid username or password.");
            return null;
        }

        return user;
    }

    private String hashPassword(String password) {

        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashedBytes = digest.digest(password.getBytes());

            StringBuilder hexString = new StringBuilder();

            for (byte b : hashedBytes) {
                String hex = Integer.toHexString(0xff & b);

                if (hex.length() == 1) {
                    hexString.append('0');
                }

                hexString.append(hex);
            }

            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

}