"""Google Play satın alma doğrulaması – sahte Google sunucusuyla (mock) test.
Kullanım: python3 test_store_mock.py http://localhost/api
(config.php'de google_play_api ve google_play_sa.token_uri sahte sunucuyu göstermeli)
"""
import sys, uuid
sys.argv = sys.argv[:2]
BASE = sys.argv[1]
import json, urllib.request, urllib.error
RUN = uuid.uuid4().hex[:6]

def call(method, path, body=None, token=None, expect=None):
    req = urllib.request.Request(BASE + path, data=json.dumps(body).encode() if body is not None else None, method=method)
    req.add_header("Content-Type", "application/json")
    if token: req.add_header("Authorization", "Bearer " + token)
    try:
        with urllib.request.urlopen(req) as r: st, p = r.status, json.loads(r.read() or b"null")
    except urllib.error.HTTPError as e: st, p = e.code, json.loads(e.read() or b"null")
    if expect is not None: assert st == expect, (path, st, p)
    elif st >= 400: raise AssertionError((path, st, p))
    return p

r = call("POST", "/auth/register", {"username": f"buyer_{RUN}", "password": "sifre1234"}, expect=201)
tok = r["token"]; b0 = r["me"]["balance"]
r2 = call("POST", "/auth/register", {"username": f"thief_{RUN}", "password": "sifre1234"}, expect=201)
assert call("GET", "/coin-packs", token=tok)["store_ready"] is True
t = f"ok-{RUN}"
p = call("POST", "/purchases/google", {"product_id": "coins_1200", "purchase_token": t}, token=tok)
assert p["coins"] == 1200 and p["balance"] == b0 + 1200 and not p["duplicate"], p
p = call("POST", "/purchases/google", {"product_id": "coins_1200", "purchase_token": t}, token=tok)
assert p["duplicate"] and p["balance"] == b0 + 1200, "aynı token iki kez yüklenmez"
call("POST", "/purchases/google", {"product_id": "coins_1200", "purchase_token": t}, token=r2["token"], expect=409)
call("POST", "/purchases/google", {"product_id": "coins_500", "purchase_token": f"pending-{RUN}"}, token=tok, expect=409)
call("POST", "/purchases/google", {"product_id": "coins_500", "purchase_token": "sahte"}, token=tok, expect=422)
call("POST", "/purchases/google", {"product_id": "yok_boyle", "purchase_token": t}, token=tok, expect=404)
p = call("POST", "/purchases/google", {"product_id": "coins_15000", "purchase_token": f"ok-2-{RUN}"}, token=tok)
assert p["coins"] == 15000 and p["balance"] == b0 + 16200
print("tamam: Google Play doğrulama (mock)")
