package dev.service;

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

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class AuthService {

    private final UserDao userDao = new UserDao();

    /**
     * Registers a new user. Checks the username is free and that the fields
     * are not empty, then stores the password as a SHA-256 hash.
     * Returns true only if the account was actually created.
     */
    public boolean register(String username, String password, String email) {

        if (username == null || username.isBlank()
                || password == null || password.isBlank()) {
            System.out.println("Username and password are required.");
            return false;
        }

        // Username must be unique.
        if (userDao.findByUsername(username) != null) {
            System.out.println("That username is already taken.");
            return false;
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(hash(password));      // never store plain text
        user.setEmail(email == null || email.isBlank() ? null : email);

        return userDao.save(user);
    }

    /**
     * Checks the given credentials against the database.
     * Returns the User on success, or null if the username does not exist
     * or the password is wrong.
     */
    public User login(String username, String password) {

        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;   // no such username
        }

        // Hash the entered password and compare with the stored hash.
        if (user.getPassword().equals(hash(password))) {
            return user;
        }

        return null;       // wrong password
    }

    /** Hashes text with SHA-256 and returns it as a lowercase hex string. */
    private String hash(String text) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] bytes = digest.digest(text.getBytes(StandardCharsets.UTF_8));

            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();

        } catch (NoSuchAlgorithmException e) {
            // SHA-256 is always available, so this should never happen.
            throw new RuntimeException("SHA-256 not available", e);
        }
    }

}
