import asyncio
import sys
from unilink import Client


async def run_smoke_test():
    BASE_URL = "http://localhost:8083/api/v1"
    TOKEN = "N4F_hwJgq9mdd4xd1CbE8aTIBYPljpDnEPAzcTzmBX0XvjjF0z28VEwjuOTr9yX1"

    client = Client(TOKEN, BASE_URL)
    test_user_id = "smoke_test_user_777"

    print("Starting unilink library test")

    try:
        print("[ ] Creating user...")
        user = await client.get_user(test_user_id)

        if user is None:
            user = await client.create_user(test_user_id)
        print(f"[+] Success. Internal ID: {user.id}")

        print("[ ] Sending message...")
        msg = await client.send_message(test_user_id, "Test hello!")
        print(f"[+] Success. Server response: {msg.response}")

        print("[ ] Getting history...")
        history = await client.get_history(test_user_id)
        assert len(history) > 0
        print(f"[+] Success. Messages found: {len(history)}")

        print("[ ] Updating data (city: Frankfurt)...")
        updated = await client.update_user(
            test_user_id,
            new_user_id="ext_ref_1",
            content={"name": "Test Name", "city": "Frankfurt"},
        )
        assert updated.external_id == "ext_ref_1"
        assert updated.content.city == "Frankfurt"

        test_user_id = updated.external_id
        print(f"[+] Success. Profile city: {updated.content.city}")

        print("[ ] Clearing message history...")
        await client.clear_history(test_user_id)
        empty_history = await client.get_history(test_user_id)
        assert len(empty_history) == 0
        print("[+] Success. History is empty.")

        print("[ ] Deleting user...")
        deleted = await client.delete_user(test_user_id)
        assert deleted.id == user.id
        assert deleted.external_id == updated.external_id
        print(f"[+] Success. User {deleted.id} deleted.")

        print("[ ] Checking user existence...")
        user = await client.get_user(test_user_id)

        assert user is None
        print("\n[!] All tests passed successfully.")

    except Exception as e:
        print(f"\n[!] Test failed: {e}")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(run_smoke_test())
