import asyncio
import sys
sys.path.insert(0, ".")

async def test_full_login():
    from common.sqlite_client import sqlite_client as db
    from common.sqlite_client import init_sqlite
    from common.jwt_auth import verify_password, create_access_token, create_refresh_token
    from datetime import datetime, timezone
    
    await init_sqlite()
    
    print("Step 1: fetch user")
    user = await db.fetch_one("SELECT * FROM cuccu_users WHERE username = ?", ("e2etest",))
    if not user:
        print("ERROR: user not found")
        return
    print(f"  user id={user['id']} role={user['role']}")
    
    print("Step 2: verify password")
    ok = verify_password("Test12345!", user["password_hash"])
    print(f"  verify_password: {ok}")
    
    print("Step 3: create tokens")
    user_id = str(user["id"])
    access_token = create_access_token(data={"sub": user_id})
    refresh_token, expires_at = create_refresh_token(data={"sub": user_id})
    print(f"  access_token: {access_token[:30]}...")
    print(f"  refresh_token: {refresh_token[:30]}...")
    print(f"  expires_at: {expires_at}")
    
    print("Step 4: insert refresh_token")
    now = datetime.now(timezone.utc).isoformat()
    try:
        cursor = await db.execute(
            "INSERT INTO cuccu_refresh_tokens (user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?)",
            (user_id, refresh_token, expires_at.isoformat(), now),
        )
        print(f"  inserted row {cursor.lastrowid}")
    except Exception as e:
        print(f"  ERROR: {e}")
    
    print("Step 5: return mock response")
    response = {
        "access_token": access_token,
        "refresh_token": refresh_token,
        "token_type": "bearer",
        "user": {
            "id": user_id,
            "username": user["username"],
            "email": user["email"],
        },
    }
    print(f"  OK: {str(response)[:100]}")

asyncio.run(test_full_login())
