package com.social.media;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.social.media.service.UserCredentialsService;
import com.social.media.repository.UserCredentialsRepository;
import com.social.media.domain.entity.UserCredentials;

@SpringBootTest
public class GeneratePasswordHash {
    
    @Autowired
    private UserCredentialsService userCredentialsService;
    
    @Autowired
    private UserCredentialsRepository userCredentialsRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Test
    public void testLiveAuthentication() {
        System.out.println("=== TESTING LIVE AUTHENTICATION ===");
        Long userId = 1L;
        String password = "admin123";
        
        System.out.println("User ID: " + userId);
        System.out.println("Password: " + password);
        
        // Let's check the credentials first
        UserCredentials credentials = userCredentialsRepository.findByUserId(userId).orElse(null);
        if (credentials != null) {
            System.out.println("Hash from DB: " + credentials.getPasswordHash());
            System.out.println("Failed attempts before: " + credentials.getFailedLoginAttempts());
            System.out.println("Account locked before: " + credentials.isAccountLocked());
            
            // Test BCrypt directly
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean directMatch = encoder.matches(password, credentials.getPasswordHash());
            System.out.println("Direct BCrypt match: " + directMatch);
            
            // Test with injected encoder
            boolean injectedMatch = passwordEncoder.matches(password, credentials.getPasswordHash());
            System.out.println("Injected encoder match: " + injectedMatch);
        }
        
        boolean result = userCredentialsService.authenticate(userId, password);
        System.out.println("Service authenticate result: " + result);
        
        // Check after authentication
        credentials = userCredentialsRepository.findByUserId(userId).orElse(null);
        if (credentials != null) {
            System.out.println("Failed attempts after: " + credentials.getFailedLoginAttempts());
            System.out.println("Account locked after: " + credentials.isAccountLocked());
        }
    }
}
