package online.wesal.wesal.service;

import online.wesal.wesal.config.JwtUtil;
import online.wesal.wesal.entity.User;
import online.wesal.wesal.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AuthService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    public String authenticate(String emailOrUsername, String password) {
        Optional<User> userOpt = userRepository.findByEmail(emailOrUsername);
        
        if (userOpt.isEmpty()) {
            userOpt = userRepository.findByUsername(emailOrUsername);
        }
        
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            System.out.println("Authenticating user: " + user.getEmail());
            if (passwordEncoder.matches(password, user.getPassword())) {
                System.out.println("Password matches!");
                if (!user.isActivated()) {
                    user.setActivated(true);
                    userRepository.save(user);
                }
                return jwtUtil.generateToken(user.getEmail());
            }
        }
        
        throw new RuntimeException("Invalid credentials");
    }
}