package online.wesal.wesal.service;

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.MulticastMessage;
import com.google.firebase.messaging.Notification;
import com.google.firebase.messaging.BatchResponse;
import online.wesal.wesal.entity.User;
import online.wesal.wesal.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SubscriptionNotificationService {

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

    @Autowired
    private UserRepository userRepository;

    @Async
    public void sendNotificationToSubscription(String subscriptionName, String title, String body) {
        try {
            // Get all users subscribed to the given subscription
            List<User> subscribedUsers = userRepository.findUsersSubscribedTo(subscriptionName);
            
            if (subscribedUsers.isEmpty()) {
                logger.info("No users found subscribed to '{}'", subscriptionName);
                return;
            }

            // Extract FCM tokens from subscribed users
            List<String> tokens = subscribedUsers.stream()
                    .map(User::getFcmToken)
                    .filter(token -> token != null && !token.trim().isEmpty())
                    .collect(Collectors.toList());

            if (tokens.isEmpty()) {
                logger.warn("No valid FCM tokens found for subscription '{}'", subscriptionName);
                return;
            }

            // Create multicast message
            MulticastMessage message = MulticastMessage.builder()
                    .setNotification(Notification.builder()
                            .setTitle(title)
                            .setBody(body)
                            .build())
                    .addAllTokens(tokens)
                    .build();

            // Send the multicast message
            BatchResponse response = FirebaseMessaging.getInstance().sendEachForMulticast(message);
            
            logger.info("Successfully sent notifications for subscription '{}': {} successful, {} failed", 
                       subscriptionName, response.getSuccessCount(), response.getFailureCount());
            
            // Log any failures for debugging
            if (response.getFailureCount() > 0) {
                for (int i = 0; i < response.getResponses().size(); i++) {
                    if (!response.getResponses().get(i).isSuccessful()) {
                        logger.error("Failed to send notification to token {}: {}", 
                                   tokens.get(i), response.getResponses().get(i).getException().getMessage());
                    }
                }
            }

        } catch (Exception e) {
            logger.error("Failed to send notifications for subscription '{}': {}", subscriptionName, e.getMessage(), e);
        }
    }

    @Async
    public void sendNotificationToUser(User user, String subscriptionName, String title, String body) {
        if (user == null || user.getFcmToken() == null || user.getFcmToken().trim().isEmpty()) {
            logger.warn("User has no valid FCM token, skipping notification");
            return;
        }

        // Check if user is subscribed
        if (!user.getSubscriptions().contains(subscriptionName)) {
            logger.debug("User {} is not subscribed to '{}', skipping notification", user.getDisplayName(), subscriptionName);
            return;
        }

        try {
            MulticastMessage message = MulticastMessage.builder()
                    .setNotification(Notification.builder()
                            .setTitle(title)
                            .setBody(body)
                            .build())
                    .addAllTokens(Collections.singletonList(user.getFcmToken()))
                    .build();

            BatchResponse response = FirebaseMessaging.getInstance().sendEachForMulticast(message);
            
            if (response.getSuccessCount() > 0) {
                logger.info("Successfully sent notification to {}", user.getDisplayName());
            } else {
                logger.error("Failed to send notification to {}: {}", 
                           user.getDisplayName(), response.getResponses().get(0).getException().getMessage());
            }

        } catch (Exception e) {
            logger.error("Failed to send notification to {}: {}", user.getDisplayName(), e.getMessage(), e);
        }
    }

    public String truncateText(String text, int maxLength) {
        if (text == null || text.length() <= maxLength) {
            return text;
        }
        return text.substring(0, maxLength).trim() + "...";
    }
}