import logging

from django.conf import settings

from django.apps import apps
from django.urls import reverse
from requests import request

logger = logging.getLogger(__name__)


def update_shop_webhooks(shop):
    """Deactivate and re-activate all configured webhooks for a shop."""
    deactivate_webhooks(shop)
    activate_webhooks(shop)


def rest_topic_to_graphql(topic):
    """Convert a REST webhook topic (e.g. 'orders/create') to GraphQL format ('ORDERS_CREATE')."""
    return topic.replace("/", "_").upper()


def webhook_activate(shop, topic, callback_url):
    """Create a webhook subscription for a single topic via the GraphQL Admin API."""
    query = """#graphql
        mutation webhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) {
            webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) {
                webhookSubscription {
                    id
                    topic
                    filter
                    format
                    includeFields
                endpoint {
                    __typename
                    ... on WebhookHttpEndpoint {
                    callbackUrl
                    }
                }
                }
                userErrors {
                    field
                    message
                }
            }
        }
    """

    subscription = {
        "callbackUrl": callback_url,
        "format": "JSON",
    }

    logger.debug("Webhook subscription: topic=%s callback_url=%s", topic, callback_url)

    variables = {
        "topic": rest_topic_to_graphql(topic),
        "webhookSubscription": subscription,
    }

    response = shop.graphql(query=query, variables=variables)

    logger.debug("Webhook response status: %s", response.status_code)


def activate_webhooks(shop):
    """Subscribe to all webhook topics defined in SHOPIFY_WEBHOOK_TOPICS."""
    config = apps.get_app_config("shopify_app")
    webhooks_path = reverse("shopify_app:webhooks")
    callback_url = f"{config.WEBHOOK_HOST}{webhooks_path}"
    for topic in settings.SHOPIFY_WEBHOOK_TOPICS:
        webhook_activate(shop, topic, callback_url)


def deactivate_webhooks(shop):
    """Remove all existing webhook subscriptions for a shop via the REST Admin API."""
    response = shop.get("/admin/api/api_version/webhooks.json")
    response.raise_for_status()
    webhooks = response.json()["webhooks"]
    for webhook in webhooks:
        shop.delete_request(f"/admin/api/api_version/webhooks/{webhook['id']}.json")
