from pyrogram import Error

from .client import get_client
from .models import Chat, AggregationSource


def aggregation_source_deleted(sender, instance: AggregationSource, **kwargs):
    if not AggregationSource.objects.filter(chat_id=instance.chat_id):
        Chat.objects.filter(chat_id=instance.chat_id).delete()


def chat_deleted(sender, instance: Chat, **kwargs):
    with get_client() as client:
        try:
            client.leave_chat(instance.chat_id)
        except Error:
            pass
