import logging

from django.db.models.signals import post_save
from django.dispatch import receiver
from firebase_admin import messaging, exceptions

from core.apps.eggs.models.notification import Notification
from core.http.models import User

logger = logging.getLogger(__name__)


@receiver(post_save, sender=Notification)
def send_notification(sender, instance, created, **kwargs):  # noqa
    if created:
        try:
            if instance.user:
                # Sending notification to a specific user
                fcm_token = instance.user.fcm_token
                if fcm_token:
                    message = messaging.Message(
                        notification=messaging.Notification(
                            title=instance.title,
                            body=instance.body,
                        ),
                        token=fcm_token,
                    )
                    messaging.send(message)
                    logger.info(f"Notification sent to user {instance.user.id}")
            else:
                # Sending notification to all users
                users = User.objects.exclude(fcm_token__isnull=True).exclude(fcm_token='')
                if users.exists():
                    messages = [
                        messaging.Message(
                            notification=messaging.Notification(
                                title=instance.title,
                                body=instance.body,
                            ),
                            token=user.fcm_token,
                        )
                        for user in users
                    ]
                    response = messaging.send_all(messages)
                    logger.info(f"{response.success_count} notifications sent successfully")
                else:
                    logger.warning("No users with valid FCM tokens found")
        except Exception as e:
            logger.error(f"Failed to send notification: {e}")
