package dev.service;

import dev.model.User;
import dev.dao.UserDao;
import java.lang.reflect.Field;
import java.security.*;

public class AuthService {
    private final UserDao userDao = new UserDao();
    public boolean register(String username, String password, String email) {

        // TODO:
        // Validate and register user
        if (userDao.findByUsername(username) != null){
            System.out.println("Error: Username already exists!");
            return false;
        }
        String hashedPassword = hashPassword(password);
        if (hashedPassword == null){
            return false;
        }
        User user = new User();
        try {
            Field usernameField = User.class.getDeclaredField("username");
            Field passwordField = User.class.getDeclaredField("password");
            Field emailField = User.class.getDeclaredField("email");
            usernameField.setAccessible(true);
            passwordField.setAccessible(true);
            emailField.setAccessible(true);
            usernameField.set(user, username);
            passwordField.set(user, hashedPassword);
            emailField.set(user, email);
            return userDao.save(user);
        }
        catch (Exception ex){
            ex.printStackTrace();
            return false;
        }
    }

    public User login(String username, String password) {

        // TODO:
        // Authenticate user
        User user = userDao.findByUsername(username);
        if (user == null){
            return null;
        }
        try {
            Field passwordField = User.class.getDeclaredField("password");
            passwordField.setAccessible(true);
            String storedPassword = (String) passwordField.get(user);

            if (storedPassword.equals(hashPassword(password))){
                return user;
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }
    private String hashPassword(String password){
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] encodedhash = digest.digest(password.getBytes());
            StringBuilder hexString = new StringBuilder(2 * encodedhash.length);
            for (byte b : encodedhash){
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        }
        catch (NoSuchAlgorithmException ex){
            ex.printStackTrace();
            return null;
        }
    }
}