import json
import urllib.request

ONEPAY_CONFIG = {
    "apiKey": "AIzaSyDpJzIe9IYb-NKYMKUaQJGXSFI2IPnNLTA",
    "projectId": "onepay-prod-1group"
}

def verify_payment(reference: str, amount: str = None, store_id: str = "default") -> dict:
    """
    Verify if a payment reference was confirmed by the merchant's 1pay relay.
    Supports full reference and 4/6-digit suffix matching (e.g. last 4 digits).
    """
    clean_ref = str(reference).strip()
    field_to_query = "referenceSuffix4" if len(clean_ref) == 4 else ("referenceSuffix6" if len(clean_ref) == 6 else "reference")
    url = f"https://firestore.googleapis.com/v1/projects/{ONEPAY_CONFIG['projectId']}/databases/(default)/documents:runQuery?key={ONEPAY_CONFIG['apiKey']}"
    
    payload = {
        "structuredQuery": {
            "from": [{"collectionId": "payments"}],
            "where": {
                "fieldFilter": {
                    "field": {"fieldPath": field_to_query},
                    "op": "EQUAL",
                    "value": {"stringValue": clean_ref}
                }
            },
            "limit": 5
        }
    }
    
    try:
        req = urllib.request.Request(
            url,
            data=json.dumps(payload).encode("utf-8"),
            headers={"Content-Type": "application/json"},
            method="POST"
        )
        with urllib.request.urlopen(req) as resp:
            results = json.loads(resp.read().decode("utf-8"))
            
        for item in results:
            if isinstance(item, dict) and "document" in item and "fields" in item["document"]:
                fields = item["document"]["fields"]
                doc_store = fields.get("storeId", {}).get("stringValue", "default")
                if store_id and doc_store != store_id:
                    continue
                doc_amount = fields.get("amount", {}).get("stringValue", "")
                if amount is not None and str(amount).strip():
                    norm_doc = doc_amount.replace(",", ".")
                    norm_exp = str(amount).strip().replace(",", ".")
                    if norm_doc != norm_exp and doc_amount != str(amount).strip():
                        continue
                return {
                    "verified": True,
                    "bank": fields.get("bank", {}).get("stringValue", "Unknown"),
                    "reference": fields.get("reference", {}).get("stringValue", clean_ref),
                    "amount": doc_amount,
                    "currency": fields.get("currency", {}).get("stringValue", "VES"),
                    "timestamp": fields.get("timestamp", {}).get("timestampValue")
                }
    except Exception as err:
        print(f"[1pay SDK] Verification failed: {err}")
        
    return {"verified": False}
