package dev.service;


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


import java.security.MessageDigest;



public class AuthService {


    private final UserDao userDao =
            new UserDao();




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



        User existingUser = userDao.findByUsername(username);

        if (existingUser != null) {
            return false;
        }


        String hashedPassword = hashPassword(password);


        User user = new User(username, hashedPassword, email);


        return userDao.save(user);
    }






    public User login(String username,
                      String password){



        User user =
                userDao.findByUsername(username);



        if(user==null){

            return null;

        }



        String hashed =
                hashPassword(password);



        if(user.getPassword().equals(hashed)){


            return user;

        }



        return null;


    }





    private String hashPassword(String password){


        try{


            MessageDigest md =
                    MessageDigest.getInstance("SHA-256");


            byte[] bytes =
                    md.digest(
                            password.getBytes()
                    );



            StringBuilder sb =
                    new StringBuilder();



            for(byte b:bytes){


                sb.append(
                        String.format("%02x",b)
                );


            }


            return sb.toString();



        }catch(Exception e){

            throw new RuntimeException(e);

        }


    }


}