from django.db import models
from django.core.validators import EmailValidator
from django.utils import timezone

from core.models import TimeStampedModel


class NewsletterSubscriber(TimeStampedModel):
    SITE_CHOICES = [
        ('lifey', 'Lifey'),
        ('planysoft', 'PlanySoft'),
    ]

    email = models.EmailField(validators=[EmailValidator()])
    site = models.CharField(max_length=20, choices=SITE_CHOICES)
    unsubscribed = models.BooleanField(default=False)
    unsubscribed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        # One email per site — same email can subscribe to both
        unique_together = [('email', 'site')]
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['email', 'site']),
            models.Index(fields=['site', 'unsubscribed']),
        ]

    def __str__(self):
        status = 'unsubscribed' if self.unsubscribed else 'active'
        return f"{self.email} ({self.site}) — {status}"
