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;

    public AuthService() {
        this.userDao = new UserDao();
    }

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

        if (username == null || username.trim().isEmpty())
        {
            System.err.println("username cannot be empty.");
            return false;
        }
        if (password == null || password.trim().isEmpty())
        {
            System.err.println("password cannot be empty.");
            return false;
        }
        User existingUser = userDao.findByUsername(username);
        if (existingUser != null)
        {
            System.err.println("a user with this username is already registered");
            return false;
        }

        String hashedPassword = hashPassword(password);
        if (hashedPassword == null)
        {
            System.err.println("error");
            return false;
        }

        User newUser = new User();
        newUser.setUsername(username.trim());
        newUser.setPassword(hashedPassword);
        newUser.setEmail(email != null ? email.trim() : null);

        return userDao.save(newUser);
    }

    public User login(String username, String password) {

        if (username == null || username.trim().isEmpty())
        {
            System.err.println("username cannot be empty.");
            return null;
        }
        if (password == null || password.trim().isEmpty())
        {
            System.err.println("password cannot be empty.");
            return null;
        }

        User user = userDao.findByUsername(username.trim());
        if (user == null)
        {
            System.err.println("not found");
            return null;
        }
        String hashedPassword = hashPassword(password);
        if (hashedPassword == null)
        {
            System.err.println("error");
            return null;
        }

        if (hashedPassword.equals(user.getPassword()))
        {
            System.out.println("welcome " + user.getUsername());
            return user;
        } else
        {
            System.err.println("incorrect password");
            return null;
        }

    }

    private String hashPassword(String password)
    {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(password.getBytes());

            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}