import logging
from django.conf import settings
from django.shortcuts import render
from django.views.decorators.http import require_POST
from hub.services.odoo import OdooAPI

logger = logging.getLogger(__name__)


@require_POST
def subscribe(request):
    """Handle mailing list subscription requests"""
    email = request.POST.get("email", "")
    if not email:
        return render(request, "subscriptions/error.html")

    try:
        # Get mailing list ID from settings
        mailing_list_id = settings.ODOO_CONFIG.get("mailing_list_id", 46)

        # Connect to Odoo
        odoo = OdooAPI()

        # Add subscriber to mailing list
        result = odoo.add_to_mailing_list(email, mailing_list_id)

        if result:
            return render(request, "subscriptions/success.html")
        else:
            return render(request, "subscriptions/error.html")

    except Exception as e:
        logger.error(
            f"Failed to add subscriber to mailing list: {str(e)}", exc_info=True
        )
        return render(request, "subscriptions/error.html")
