package com.storycove.service;

import com.storycove.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class PasswordAuthenticationService {
    
    private static final Logger logger = LoggerFactory.getLogger(PasswordAuthenticationService.class);
    
    private final PasswordEncoder passwordEncoder;
    private final LibraryService libraryService;
    private final JwtUtil jwtUtil;
    
    @Autowired
    public PasswordAuthenticationService(
            PasswordEncoder passwordEncoder, 
            LibraryService libraryService,
            JwtUtil jwtUtil) {
        this.passwordEncoder = passwordEncoder;
        this.libraryService = libraryService;
        this.jwtUtil = jwtUtil;
    }
    
    /**
     * Authenticate user and switch to the appropriate library
     * Returns JWT token if authentication successful, null otherwise
     */
    public String authenticateAndSwitchLibrary(String providedPassword) {
        if (providedPassword == null || providedPassword.trim().isEmpty()) {
            return null;
        }
        
        // Find which library this password belongs to
        String libraryId = libraryService.authenticateAndGetLibrary(providedPassword);
        if (libraryId == null) {
            logger.warn("Authentication failed - invalid password");
            return null;
        }
        
        try {
            // Switch to the authenticated library with forced reindexing (may take 2-3 seconds)
            libraryService.switchToLibraryAfterAuthentication(libraryId);
            
            // Generate JWT token with library context
            String token = jwtUtil.generateToken("user", libraryId);
            
            logger.info("Successfully authenticated and switched to library: {}", libraryId);
            return token;
            
        } catch (Exception e) {
            logger.error("Failed to switch to library: {}", libraryId, e);
            return null;
        }
    }
    
    /**
     * Legacy method - kept for backward compatibility
     */
    @Deprecated
    public boolean authenticate(String providedPassword) {
        return authenticateAndSwitchLibrary(providedPassword) != null;
    }
    
    public String encodePassword(String rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }
    
    /**
     * Get current library info for authenticated user
     */
    public String getCurrentLibraryInfo() {
        var library = libraryService.getCurrentLibrary();
        if (library != null) {
            return String.format("Library: %s (%s)", library.getName(), library.getId());
        }
        return "No library active";
    }
}