from django.urls import reverse_lazy
from django.views.generic import CreateView
from backend.accounts.forms import SignupForm
from .models import EmailConfirmation
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from backend.accounts.utils import send_confirmation_email
from .tasks import create_document_for_organization
from backend.core.models import Organization, Document

class SignUpView(CreateView):
    form_class = SignupForm
    success_url = reverse_lazy('login')
    template_name = 'accounts/signup.html'


def confirm_email(request, uuid):
    confirmation = get_object_or_404(EmailConfirmation, uuid=uuid)

    if confirmation.is_expired():
        return render(request, 'accounts/confirmation_expired.html', {'email': confirmation.email})
    
    if confirmation.confirmed:
        return render(request, 'accounts/confirmation_success.html', {'email': confirmation.email})
    
    confirmation.confirmed = True
    confirmation.save()

    org = Organization.objects.filter(email=confirmation.email).first()
    if org and Document.objects.filter(organization=org).exists():
        return render(request, 'accounts/confirmation_success.html', {'email': confirmation.email})
    else:
        task = create_document_for_organization.delay(confirmation.email)
        return render(request, 'accounts/confirmation_success.html', {'email': confirmation.email})

def resend_confirmation(request,email):
    if request.method == 'POST':
        send_confirmation_email(email)
        return HttpResponse("Confirmation email resent")