package com.server.api.service;

import com.server.api.models.User;
import com.server.api.repository.AuthRepository;
import com.server.api.utils.HashUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;


@Service
public class AuthService {

    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);

    @Autowired
    private AuthRepository authRepository;

    public boolean signUp(User user) {

        try {
            // Validate user object (you can implement your own validation logic)
            if (user == null || user.getName() == null || user.getPassword() == null) {
                throw new IllegalArgumentException("User or required fields cannot be null");
            }

            // Hash password
            user.setPassword(HashUtil.hash(user.getPassword()));

            // Save the user to the repository
            authRepository.save(user);
            return true;
        } catch (Exception e) {
            logger.error("Error during sign up: ", e); // Log the exception
            return false;
        }
    }

    public boolean signIn(User user) {
        if (user == null || user.getName() == null || user.getPassword() == null) {
            return false;
        }

        try {
            Optional<User> maybe = Optional.ofNullable(authRepository.findByName(user.getName()));
            if (maybe.isEmpty()) return false;

            User stored = maybe.get();
            // Hash das eingegebene Passwort und vergleiche mit gespeichertem Hash
            String hashedInput = HashUtil.hash(user.getPassword());
            return hashedInput.equals(stored.getPassword());
        } catch (Exception e) {
            logger.error("Error during sign in: ", e);
            return false;
        }
    }

}
