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


class WaitlistForm(forms.Form):
    """
    Step 1: Email submission.
    Standalone Form (not ModelForm) — we handle the get_or_create logic
    in the view, so we only need to validate the email here.
    Rejects already-verified emails early to avoid a pointless code send.
    """
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'required': True}),
    )

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

        existing = WaitlistEntry.objects.filter(email=email).first()
        if existing and existing.verified:
            raise ValidationError('This email is already on the waitlist.')

        return email


class WaitlistVerificationForm(forms.Form):
    """
    Step 2: Code submission.
    email comes back as a hidden field from the frontend after step 1.
    """
    email = forms.EmailField(
        widget=forms.HiddenInput(),
    )
    code = forms.CharField(
        max_length=6,
        min_length=6,
        widget=forms.TextInput(attrs={
            'inputmode': 'numeric',
            'maxlength': '6',
            'autocomplete': 'one-time-code',
        }),
    )

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

    def clean_code(self):
        code = self.cleaned_data['code'].strip()
        if not code.isdigit():
            raise ValidationError('Verification code must contain only digits.')
        return code


class ResendVerificationForm(forms.Form):
    """
    Resend request: only needs the email.
    View intentionally returns a neutral response regardless of outcome
    to prevent email enumeration.
    """
    email = forms.EmailField()

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