from django.utils.translation import gettext_lazy as _
from mollie.api.error import ResponseError

from oscar.apps.order import exceptions

from ocyan.main.loading import get_baseclass

BaseEventHandler = get_baseclass(
    "order.processing", "EventHandler", "ocyan.plugin.payment_mollie.mollie_order_ext"
)


class EventHandler(BaseEventHandler):
    def handle_shipping_event(
        self, order, event_type, lines, line_quantities, **kwargs
    ):
        # import here because ocyan.plugin.oscar.utils is imported later
        from ocyan.plugin.payment_mollie.mollie_payment import MolliePayment

        event = super().handle_shipping_event(
            order, event_type, lines, line_quantities, **kwargs
        )

        mollie_sources = order.sources.filter(source_type__code__startswith="mollie:")
        if mollie_sources.exists():
            reference = mollie_sources.first().reference
            if reference.startswith("ord_"):
                try:
                    mollie = MolliePayment()
                    mollie.create_shipment(reference)
                except ResponseError:
                    raise exceptions.InvalidShippingEvent(
                        _(
                            "Something went wrong while sending order to Mollie, is the order authorized in mollie?"
                        )
                    )

        return event
