from django.db import models
from django.conf import settings


class Notification(models.Model):
    """Notification model for user alerts"""

    NOTIFICATION_TYPES = (
        ('follow', 'New Follower'),
        ('like', 'Product Liked'),
        ('comment', 'New Comment'),
        ('reply', 'Comment Reply'),
        ('order', 'Order Update'),
        ('system', 'System Notification'),
        ('promotion', 'Promotion Alert'),
        ('message', 'New Message'),
        ('group_post', 'Group Post'),
        ('group_comment', 'Group Comment'),
        ('group_mention', 'Group Mention'),
        ('group_join_approved', 'Group Join Approved'),
        ('group_join_request', 'Group Join Request'),
        ('group_announcement', 'Group Announcement'),
        ('group_invitation', 'Group Invitation'),
        ('welcome', 'Welcome'),
        ('upgrade', 'Pro Upgrade'),
        ('verification', 'Verification Update'),
        ('live_scheduled', 'Live Scheduled'),
        ('live_started', 'Live Started'),
        ('live_reminder', 'Live Reminder'),
    )

    recipient = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='notifications'
    )
    sender = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='sent_notifications'
    )
    notification_type = models.CharField(max_length=20, choices=NOTIFICATION_TYPES)
    title = models.CharField(max_length=200)
    message = models.TextField()
    link = models.CharField(max_length=500, blank=True, null=True, help_text="Deep link URL")

    # Reference to related objects (optional)
    product_id = models.IntegerField(null=True, blank=True)
    comment_id = models.IntegerField(null=True, blank=True)

    is_read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'notifications'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.notification_type} - {self.recipient.full_name}: {self.title}"

    @classmethod
    def create_notification(cls, recipient, notification_type, title, message, sender=None, link=None, product_id=None, comment_id=None):
        """Helper method to create notifications"""
        return cls.objects.create(
            recipient=recipient,
            sender=sender,
            notification_type=notification_type,
            title=title,
            message=message,
            link=link,
            product_id=product_id,
            comment_id=comment_id,
        )

    @classmethod
    def notify_follow(cls, vendor_user, follower):
        """Create notification for new follower"""
        return cls.create_notification(
            recipient=vendor_user,
            sender=follower,
            notification_type='follow',
            title='New Follower',
            message=f'{follower.full_name} started following your shop.',
            link=f'/buyer/{follower.id}' if hasattr(follower, 'buyer_profile') else None,
        )

    @classmethod
    def notify_like(cls, product_owner, liker, product):
        """Create notification for product like"""
        return cls.create_notification(
            recipient=product_owner,
            sender=liker,
            notification_type='like',
            title='Product Liked',
            message=f'{liker.full_name} liked your product "{product.name}".',
            link=f'/product/{product.uuid}',
            product_id=product.id,
        )

    @classmethod
    def notify_comment(cls, product_owner, commenter, product, comment):
        """Create notification for new comment"""
        return cls.create_notification(
            recipient=product_owner,
            sender=commenter,
            notification_type='comment',
            title='New Comment',
            message=f'{commenter.full_name} commented on your product "{product.name}".',
            link=f'/product/{product.uuid}',
            product_id=product.id,
            comment_id=comment.id,
        )

    @classmethod
    def notify_reply(cls, comment_owner, replier, product, comment):
        """Create notification for comment reply"""
        return cls.create_notification(
            recipient=comment_owner,
            sender=replier,
            notification_type='reply',
            title='New Reply',
            message=f'{replier.full_name} replied to your comment on "{product.name}".',
            link=f'/product/{product.uuid}',
            product_id=product.id,
            comment_id=comment.id,
        )

    @classmethod
    def notify_message(cls, recipient, sender, conversation_id):
        """Create notification for new message"""
        return cls.create_notification(
            recipient=recipient,
            sender=sender,
            notification_type='message',
            title='New Message',
            message=f'{sender.full_name} sent you a message.',
            link=f'/chat/{conversation_id}',
        )

    @classmethod
    def notify_group_post(cls, group, author, post):
        """Notify group members about a new post"""
        from groups.models import GroupMembership
        members = GroupMembership.objects.filter(
            group=group, status='active'
        ).exclude(user=author).select_related('user')
        for membership in members[:50]:
            cls.create_notification(
                recipient=membership.user,
                sender=author,
                notification_type='group_post',
                title='New Group Post',
                message=f'{author.full_name} posted in {group.name}.',
                link=f'/groups/{group.slug}',
            )

    @classmethod
    def notify_group_comment(cls, recipient, commenter, post, comment):
        """Notify about a comment on a group post"""
        return cls.create_notification(
            recipient=recipient,
            sender=commenter,
            notification_type='group_comment',
            title='New Group Comment',
            message=f'{commenter.full_name} commented on a post in {post.group.name}.',
            link=f'/groups/{post.group.slug}',
        )

    @classmethod
    def notify_group_join_request(cls, admin_user, requester, group):
        """Notify admin about a join request"""
        return cls.create_notification(
            recipient=admin_user,
            sender=requester,
            notification_type='group_join_request',
            title='Join Request',
            message=f'{requester.full_name} wants to join {group.name}.',
            link=f'/groups/{group.slug}/pending-members',
        )

    @classmethod
    def notify_group_join_approved(cls, user, group):
        """Notify user their join request was approved"""
        return cls.create_notification(
            recipient=user,
            notification_type='group_join_approved',
            title='Join Approved',
            message=f'You have been approved to join {group.name}.',
            link=f'/groups/{group.slug}',
        )

    @classmethod
    def notify_group_announcement(cls, group, post):
        """Notify all members about an announcement"""
        from groups.models import GroupMembership
        members = GroupMembership.objects.filter(
            group=group, status='active'
        ).exclude(user=post.author).select_related('user')
        for membership in members[:100]:
            cls.create_notification(
                recipient=membership.user,
                sender=post.author,
                notification_type='group_announcement',
                title='Group Announcement',
                message=f'New announcement in {group.name}.',
                link=f'/groups/{group.slug}',
            )

    @classmethod
    def notify_group_invitation(cls, invitee, inviter, group):
        """Notify user about a group invitation"""
        return cls.create_notification(
            recipient=invitee,
            sender=inviter,
            notification_type='group_invitation',
            title='Group Invitation',
            message=f'{inviter.full_name} invited you to join {group.name}.',
            link=f'/groups/{group.slug}',
        )

    @classmethod
    def notify_welcome(cls, user):
        """Create welcome notification for new user"""
        user_type = user.user_type
        if user_type == 'vendor':
            message = 'Welcome to Wananchimart! Your vendor account is ready. Start adding products to your shop.'
            link = '/vendor'
        else:
            message = 'Welcome to Wananchimart! Start exploring products from local vendors.'
            link = '/explore'
        return cls.create_notification(
            recipient=user,
            notification_type='welcome',
            title='Welcome to Wananchimart!',
            message=message,
            link=link,
        )

    @classmethod
    def notify_upgrade(cls, user):
        """Create notification for successful pro upgrade"""
        return cls.create_notification(
            recipient=user,
            notification_type='upgrade',
            title='Pro Upgrade Successful!',
            message='You are now a Pro vendor! Enjoy unlimited products, multiple images, video uploads, and more.',
            link='/vendor',
        )

    @classmethod
    def notify_verification_submitted(cls, user):
        """Create notification when verification request is submitted"""
        return cls.create_notification(
            recipient=user,
            notification_type='verification',
            title='Verification Submitted',
            message='Your verification request has been submitted and is under review. You will be notified once it is approved.',
            link='/vendor/verify',
        )

    @classmethod
    def notify_verification_approved(cls, user):
        """Create notification when verification is approved"""
        return cls.create_notification(
            recipient=user,
            notification_type='verification',
            title='Verification Approved!',
            message='Congratulations! Your business has been verified. A verified badge is now displayed on your profile and shop.',
            link='/vendor/verify',
        )

    @classmethod
    def notify_live_scheduled(cls, recipient, vendor, session_title, session_slug):
        """Notify follower about a scheduled live"""
        shop_name = vendor.full_name
        try:
            shop_name = vendor.vendor_profile.shop_name
        except Exception:
            pass
        return cls.create_notification(
            recipient=recipient,
            sender=vendor,
            notification_type='live_scheduled',
            title='Live Scheduled',
            message=f'{shop_name} has scheduled a live: {session_title}',
            link=f'/live/{session_slug}',
        )

    @classmethod
    def notify_live_started(cls, recipient, vendor, session_title, session_slug):
        """Notify follower that vendor has gone live"""
        shop_name = vendor.full_name
        try:
            shop_name = vendor.vendor_profile.shop_name
        except Exception:
            pass
        return cls.create_notification(
            recipient=recipient,
            sender=vendor,
            notification_type='live_started',
            title='Live Now!',
            message=f'{shop_name} is now live: {session_title}',
            link=f'/live/{session_slug}',
        )

    @classmethod
    def notify_live_reminder(cls, recipient, vendor, session_title, session_slug):
        """Remind follower about upcoming live"""
        shop_name = vendor.full_name
        try:
            shop_name = vendor.vendor_profile.shop_name
        except Exception:
            pass
        return cls.create_notification(
            recipient=recipient,
            sender=vendor,
            notification_type='live_reminder',
            title='Live Starting Soon',
            message=f'{shop_name} is going live soon: {session_title}',
            link=f'/live/{session_slug}',
        )

    @classmethod
    def notify_verification_rejected(cls, user, reason=''):
        """Create notification when verification is rejected"""
        msg = 'Your verification request was not approved.'
        if reason:
            msg += f' Reason: {reason}'
        msg += ' You can resubmit with updated information.'
        return cls.create_notification(
            recipient=user,
            notification_type='verification',
            title='Verification Not Approved',
            message=msg,
            link='/vendor/verify',
        )
