from django import forms
from django.core.exceptions import ValidationError
from .models import NewsletterSubscriber


class NewsletterSubscribeForm(forms.Form):
    """
    Standalone form (not ModelForm) so we control error messages cleanly
    and handle the re-subscribe case without hitting a DB unique constraint.
    """
    SITE_CHOICES = [
        ('lifey', 'Lifey'),
        ('planysoft', 'PlanySoft'),
    ]

    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'required': True}),
    )
    site = forms.ChoiceField(
        choices=SITE_CHOICES,
        widget=forms.HiddenInput(),
    )

    def clean_email(self):
        return self.cleaned_data['email'].lower().strip()

    def clean(self):
        cleaned = super().clean()
        email = cleaned.get('email')
        site = cleaned.get('site')

        if not email or not site:
            return cleaned

        existing = NewsletterSubscriber.objects.filter(email=email, site=site).first()

        if existing:
            if not existing.unsubscribed:
                raise ValidationError('This email is already subscribed.')
            # Re-subscribe case: flag it on the form for the view to handle
            self._resubscribe_instance = existing
        else:
            self._resubscribe_instance = None

        return cleaned

    def save(self):
        """
        Returns the NewsletterSubscriber instance.
        Handles both new subscriptions and re-subscriptions.
        """
        email = self.cleaned_data['email']
        site = self.cleaned_data['site']

        existing = getattr(self, '_resubscribe_instance', None)

        if existing:
            existing.unsubscribed = False
            existing.unsubscribed_at = None
            existing.save(update_fields=['unsubscribed', 'unsubscribed_at'])
            return existing, False  # (instance, created)

        subscriber = NewsletterSubscriber.objects.create(email=email, site=site)
        return subscriber, True  # (instance, created)


class NewsletterUnsubscribeForm(forms.Form):
    """Unsubscribe form — only needs email and site."""
    SITE_CHOICES = [
        ('lifey', 'Lifey'),
        ('planysoft', 'PlanySoft'),
    ]

    email = forms.EmailField()
    site = forms.ChoiceField(
        choices=SITE_CHOICES,
        widget=forms.HiddenInput(),
    )

    def clean_email(self):
        return self.cleaned_data['email'].lower().strip()