from django.dispatch import receiver

import logging


from django.dispatch import receiver
from .custom_signals import order_confirmed
import logging
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from orders.models import Orders
from shops.models import Shop

@receiver(order_confirmed)
def order_notification(sender, **kwargs):
    try:
        order_id   = kwargs.get("order_id")
        store_id   = kwargs.get("store_id")
        platform   = kwargs.get("platform", "Web")
        order_type = kwargs.get("order_type", "Local Orders")
        user_ids   = []

        shop = Shop.objects.filter(uuid=store_id).first()
        if shop:
            try:
                shop_admins = shop.unit_admin_user.all()
                for i in shop_admins:
                    user_ids.append(str(i.uuid))
            except:
                pass

        order_count = Orders.objects.filter(
            order_status="Confirmed",
            store_uuid__uuid=store_id
        ).count()

        send_db_update_notification("notification", {
            "order_id":   order_id,
            "count":      order_count,
            "user_ids":   user_ids,    # ✅ shop admins only
            "platform":   platform,    # ✅ now passed correctly
            "order_type": order_type   # ✅ now passed correctly
        })

    except Exception as e:
        logging.info(f"Signal Calling Issue: {e}")



def send_db_update_notification(message_type, msg):
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "notifications",
        {
            "type": "send_notification",
            "message": msg,
            "msg_type": message_type
        }
    )
    logging.info("Notification Sent to Channel Layer")