package dev.service;

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

import java.util.Objects;

public class AuthService {

    private final UserDao userDao = new UserDao();

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

        if (!isValidEmail(email)){
            System.err.println("Invalid email address.");
            return false;
        }
        User user = new User(
                username,
                String.valueOf(password.hashCode()),
                email
        );

        if (userDao.save(user)){
            System.out.println("Successfully registered user");
            return true;
        }
        return false;
    }

    public User login(String username, String password) {

        User dbUser = userDao.findByUsername(username);

        if (dbUser == null){
            return null;
        }

        String dbUserPasswordHash = dbUser.getPasswordHash();

        if (Objects.equals(dbUserPasswordHash,
                String.valueOf(password.hashCode()))){
            return dbUser;
        }

        return null;
    }


    public boolean isValidEmail(String email) {
        if (email == null || email.isBlank()) {
            return true;
        }

        int atIndex = email.indexOf('@');
        if (atIndex <= 0) return false;
        int dotIndex = email.lastIndexOf('.');
        if (dotIndex <= atIndex + 1) return false;
        if (dotIndex == email.length() - 1) return false;

        return true;
    }
}