import json
import logging

from django.http import Http404
from django.template.response import TemplateResponse
from django.utils.safestring import mark_safe
from django.views.generic import View

from haso_payment.commerce.checkout import CheckoutService
from haso_payment.forms import HasoPaymentForm

logger = logging.getLogger(__name__)


class HasoPaymentView(View):
    checkout_service = CheckoutService()
    http_method_names = ["get"]

    def get(self, request):
        session_id = request.GET.get("sessionId")
        if not session_id:
            logging.exception("Missing sessionId")
            raise Http404

        try:
            extension_url, body = self.checkout_service.get_form_data(request)
            data = json.dumps(body, ensure_ascii=False)
            payment_form = HasoPaymentForm(initial={"data": data})
        except Exception as e:
            logging.exception(f"Error retrieving form data: {e}")
            raise Http404

        payment_form_html = payment_form.as_table()
        return TemplateResponse(
            request=request,
            template="haso_payment.html",
            context={
                "action_url": (
                    f"{extension_url}/form-page?sessionId={session_id}"
                ),
                "action_method": "POST",
                "payment_form_html": mark_safe(payment_form_html),
            }
        )
