package online.wesal.wesal.service;

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import online.wesal.wesal.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FCMNotificationService {

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

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

        try {
            Message message = Message.builder()
                    .setToken(user.getFcmToken())
                    .setNotification(Notification.builder()
                            .setTitle(title)
                            .setBody(body)
                            .build())
                    .build();


            String response = FirebaseMessaging.getInstance().send(message);
            logger.info("Successfully sent notification to {}: {}", user.getDisplayName(), response);
        } catch (Exception e) {
            logger.error("Failed to send notification to {}: {}", user.getDisplayName(), e.getMessage());
        }
    }

    @Async
    public void sendNotificationToUsers(List<User> users, String title, String body) {
        users.forEach(user -> sendNotificationToUser(user, title, body));
    }

    @Async
    public void sendInvitationAcceptedNotification(String organizerToken, String organizerName, String accepterName, String tagName) {
        String title = "New Attendee! 🎉";
        String body = String.format("%s accepted your invite for %s", accepterName, tagName);
        
        if (organizerToken == null || organizerToken.trim().isEmpty()) {
            logger.warn("User {} has no FCM token, skipping notification", organizerName);
            return;
        }

        try {
            Message message = Message.builder()
                    .setToken(organizerToken)
                    .setNotification(Notification.builder()
                            .setTitle(title)
                            .setBody(body)
                            .build())
                    .build();

            String response = FirebaseMessaging.getInstance().send(message);
            logger.info("Successfully sent notification to {}: {}", organizerName, response);
        } catch (Exception e) {
            logger.error("Failed to send notification to {}: {}", organizerName, e.getMessage());
        }
    }

    @Async
    public void sendInvitationFullNotification(List<String> fcmTokens, List<String> displayNames, String tagName, int totalAttendees) {
        String title = String.format("You're set for %s! 🚀", tagName);
        String body = String.format("%d people have accepted the invitation. Click to see who they are!", totalAttendees);
        
        for (int i = 0; i < fcmTokens.size(); i++) {
            String token = fcmTokens.get(i);
            String name = displayNames.get(i);
            
            if (token == null || token.trim().isEmpty()) {
                logger.warn("User {} has no FCM token, skipping notification", name);
                continue;
            }

            try {
                Message message = Message.builder()
                        .setToken(token)
                        .setNotification(Notification.builder()
                                .setTitle(title)
                                .setBody(body)
                                .build())
                        .build();

                String response = FirebaseMessaging.getInstance().send(message);
                logger.info("Successfully sent notification to {}: {}", name, response);
            } catch (Exception e) {
                logger.error("Failed to send notification to {}: {}", name, e.getMessage());
            }
        }
    }

}