package de.assecutor.votianlt.pages.service;

import com.vaadin.flow.component.notification.Notification;
import de.assecutor.votianlt.model.User;
import de.assecutor.votianlt.pages.domain.LoginRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.Clock;
import java.util.Optional;

@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class LoginService {

    private final LoginRepository loginRepository;
    private final PasswordEncoder passwordEncoder;

    LoginService(LoginRepository loginRepository, PasswordEncoder passwordEncoder, Clock clock) {
        this.loginRepository = loginRepository;
        this.passwordEncoder = passwordEncoder;
    }

    public Optional<User> findUser(String email, String password) {
        var userOpt = loginRepository.findByEmail(email);

        if (userOpt.isPresent()) {
            User user = userOpt.get();
            // Prüfe das Passwort mit BCrypt
            if (passwordEncoder.matches(password, user.getPassword())) {
                return Optional.of(user);
            }
        }

        Notification.show("Login failed", 3000, Notification.Position.BOTTOM_END);
        return Optional.empty();
    }
}
