"""
Сигналы для материалов.
"""

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
import logging

logger = logging.getLogger(__name__)


@receiver(post_save, sender='materials.Material')
def update_storage_quota_on_material_save(sender, instance, created, **kwargs):
    """
    Обновление квоты хранилища при создании/обновлении материала.
    """
    from .services import StorageService
    from .models import StorageQuota
    
    if instance.file and instance.owner:
        if created:
            # Новый материал - добавляем использование
            StorageService.add_file_usage(instance.owner, instance.file_size or 0)
        else:
            # Обновление материала - пересчитываем квоту
            quota, created = StorageQuota.objects.get_or_create(user=instance.owner)
            quota.recalculate()


@receiver(post_delete, sender='materials.Material')
def update_storage_quota_on_material_delete(sender, instance, **kwargs):
    """
    Обновление квоты хранилища при удалении материала.
    """
    from .services import StorageService
    
    if instance.file and instance.owner:
        StorageService.remove_file_usage(instance.owner, instance.file_size or 0)


@receiver(post_save, sender='subscriptions.Subscription')
def sync_storage_quota_on_subscription_change(sender, instance, created, **kwargs):
    """
    Синхронизация квоты хранилища при изменении подписки.
    """
    from .services import StorageService
    
    if instance.status == 'active' and instance.user:
        StorageService.sync_quota_with_subscription(instance.user)
        logger.info(f'Storage quota synced for user {instance.user.id} after subscription change')

