
import hashlib
import hmac
import json

import requests
from flask import Flask, jsonify, request

# Import Shopify GraphQL Client
from V2.functions.Shopify.main import (ShopifyGraphQLClient,
                                       getShopifyShopByDomain)
from V2.functions.Shopify.Webhooks.Orders import (handle_order_created,
                                                  handle_order_updated)

# Shopify Credentials (Replace with actual values)
SHOPIFY_WEBHOOK_SECRET = "your-webhook-secret"

# Initialize GraphQL Client

def verify_webhook(data, hmac_header):
    """Verify Shopify webhook HMAC signature."""
    calculated_hmac = hmac.new(
        SHOPIFY_WEBHOOK_SECRET.encode('utf-8'),
        data,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(calculated_hmac, hmac_header)

def shopify_webhook():
    """Unified Shopify webhook handler for all events."""
    try:
        raw_data = request.data
        hmac_header = request.headers.get('X-Shopify-Hmac-Sha256')
        event_type = request.headers.get('X-Shopify-Topic')  # Get event type
        shop_domain = request.headers.get('X-Shopify-Shop-Domain')  # Shopify store
        shop = getShopifyShopByDomain(shop_domain)
        # Verify webhook authenticity
        if not verify_webhook(raw_data, hmac_header): return jsonify({"error": "Unauthorized"}), 401

        # Parse webhook payload
        payload = json.loads(raw_data)

        # Handle different event types
        if event_type == "orders/create": handle_order_created(shop,payload)
        elif event_type == "orders/updated": handle_order_updated(payload)
        print(f"Unhandled event: {event_type}")
        return jsonify({"message": f"Webhook {event_type} processed successfully"}), 200

    except Exception as e:
        print("Error processing webhook:", str(e))
        return jsonify({"error": str(e)}), 500
