# -*- coding: utf-8; -*-
################################################################################
#
#  WuttaFarm --Web app to integrate with and extend farmOS
#  Copyright © 2026 Lance Edgar
#
#  This file is part of WuttaFarm.
#
#  WuttaFarm is free software: you can redistribute it and/or modify it under
#  the terms of the GNU General Public License as published by the Free Software
#  Foundation, either version 3 of the License, or (at your option) any later
#  version.
#
#  WuttaFarm is distributed in the hope that it will be useful, but WITHOUT ANY
#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
#  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along with
#  WuttaFarm.  If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
Views for use as webhooks
"""

import logging
from uuid import UUID

from wuttaweb.views import View
from wuttaweb.db import Session


log = logging.getLogger(__name__)


class WebhookView(View):
    """
    Webhook views
    """

    def farmos_webhook(self):
        model = self.app.model
        session = Session()

        try:
            data = self.request.json
            log.debug("got webhook payload: %s", data)

            _, entity_type, event_type = data["event"].split(":")

            uuid = data["entity"]["uuid"][0]["value"]
            if entity_type == "taxonomy_term":
                bundle = data["entity"]["vid"][0]["target_id"]
            else:
                bundle = data["entity"]["type"][0]["target_id"]

            change = model.WebhookChange(
                entity_type=entity_type,
                bundle=bundle,
                farmos_uuid=UUID(uuid),
                deleted=event_type == "delete",
            )
            session.add(change)

        except:
            log.exception("failed to process webhook request")

        return {}

    @classmethod
    def defaults(cls, config):
        cls._webhook_defaults(config)

    @classmethod
    def _webhook_defaults(cls, config):

        # farmos webhook
        config.add_route("webhooks.farmos", "/farmos/webhook", request_method="POST")
        config.add_view(
            cls,
            attr="farmos_webhook",
            route_name="webhooks.farmos",
            require_csrf=False,
            renderer="json",
        )


def defaults(config, **kwargs):
    base = globals()

    WebhookView = kwargs.get("WebhookView", base["WebhookView"])
    WebhookView.defaults(config)


def includeme(config):
    defaults(config)
