import hashlib
import hmac
import json
from flask import request, jsonify

class PaddleWebhook:
    def __init__(self, shared_secret):
        self.shared_secret = shared_secret
    
    def verify_webhook(self, request_data):
        signature = request_data.get('p_signature')
        
        if not signature:
            return False
        
        fields = dict(request_data)
        if 'p_signature' in fields:
            del fields['p_signature']
        
        sorted_fields = sorted(fields.items())
        query_string = ""
        for key, value in sorted_fields:
            if isinstance(value, list):
                value = value[0]
            query_string += f"{key}={value}"
        
        expected_signature = hmac.new(
            self.shared_secret.encode('utf-8'),
            query_string.encode('utf-8'),
            hashlib.sha1
        ).hexdigest()
        
        return hmac.compare_digest(signature, expected_signature)
    
    def parse_webhook_data(self, request_data):
        alert_name = request_data.get('alert_name')
        
        if alert_name == 'payment_succeeded':
            return {
                'event': 'payment_succeeded',
                'order_id': request_data.get('order_id'),
                'product_id': request_data.get('product_id'),
                'customer_email': request_data.get('email'),
                'customer_name': request_data.get('customer_name'),
                'amount': float(request_data.get('sale_gross', 0)),
                'currency': request_data.get('currency'),
                'passthrough': request_data.get('passthrough')
            }
        
        elif alert_name == 'payment_refunded':
            return {
                'event': 'payment_refunded',
                'order_id': request_data.get('order_id'),
                'refund_amount': float(request_data.get('refund_amount', 0))
            }
        
        return None
    
    def handle_webhook(self, request_obj):
        if request_obj.content_type == 'application/json':
            data = request_obj.get_json()
        else:
            data = request_obj.form.to_dict()
        
        if not self.verify_webhook(data):
            return {'error': 'Invalid signature'}, 403
        
        webhook_data = self.parse_webhook_data(data)
        
        if not webhook_data:
            return {'error': 'Unknown event type'}, 400
        
        return webhook_data, 200
