from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.cache import cache
from .models import Payment, ExpenseCategory
from .utils import apply_payment
from accounts.models import User
from payments.models import Expense
from core.models import ActivityLog
from utils.notifications import send_sms, send_email

# ================= PAYMENT SIGNAL =================
@receiver(post_save, sender=Payment)
def handle_payment(sender, instance, created, **kwargs):
    if not created:
        return

    # ✅ Apply payment safely
    apply_payment(instance)

    # ✅ Update invoice status
    if instance.invoice:
        instance.invoice.update_status()

    tenant = instance.tenant

    message = f"Payment of KES {instance.amount} received."

    # SMS
    if tenant.phone_number:
        send_sms(tenant.phone_number, message)

    # Email
    if tenant.email:
        send_email(tenant.email, "Payment Confirmation", message)

    # Activity log
    ActivityLog.objects.create(
        user=tenant,
        action='payment',
        description=f"Payment of {instance.amount} received"
    )


# ================= DEFAULT EXPENSE CATEGORIES =================
@receiver(post_save, sender=User)
def create_default_categories(sender, instance, created, **kwargs):
    if created and instance.role == "landlord":
        for cat in ExpenseCategory.DEFAULT_CATEGORIES:
            ExpenseCategory.objects.get_or_create(
                name=cat,
                created_by=instance,
                is_default=True
            )


@receiver(post_save, sender=Payment)
def clear_cache_on_payment(sender, **kwargs):
    cache.clear()

@receiver(post_save, sender=Expense)
def clear_cache_on_expense(sender, **kwargs):
    cache.clear()