import json, urllib.request, urllib.error

PB = "http://localhost:8102"

def req(path, data=None, token=None, method=None):
    m = method or ("POST" if data is not None else "GET")
    r = urllib.request.Request(PB + path, data=(json.dumps(data).encode() if data is not None else None),
        headers={"Content-Type": "application/json", **({"Authorization": token} if token else {})}, method=m)
    try:
        return json.load(urllib.request.urlopen(r))
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        print(f"HTTP {e.code} en {path}:\n{body}\n")
        raise

tok = req("/api/collections/_superusers/auth-with-password",
          {"identity": "edelmar.edd@gmail.com", "password": "564712564712"})["token"]

# Un pedido real
ped = req("/api/collections/pedidos/records?perPage=1", token=tok)["items"][0]
print("Pedido de prueba:", ped["id"], ped.get("codigo"))

# Un user admin para impersonar
users = req("/api/collections/users/records?perPage=1&filter=" + urllib.parse.quote('role="admin"'), token=tok)["items"]
if not users:
    print("No hay user admin"); raise SystemExit
uid = users[0]["id"]
print("User admin:", uid, users[0].get("name"))

imp = req(f"/api/collections/users/impersonate/{uid}", {}, token=tok)
utok = imp["token"]

# Intentar crear consulta como ese user
print("\n--- Intentando crear consulta como user admin ---")
try:
    c = req("/api/collections/consultas/records",
            {"pedido": ped["id"], "tipo": "consulta", "nota": "PRUEBA diagnostico", "fecha": "2026-06-08", "created_by": uid},
            token=utok)
    print("OK creada:", c["id"])
    # limpiar
    req(f"/api/collections/consultas/records/{c['id']}", token=utok, method="DELETE")
    print("(borrada la de prueba)")
except urllib.error.HTTPError:
    print("=> FALLO el create (ver error arriba)")
