print("payload_db.py loaded")

from plugins.database import db


# =========================
# GET COLLECTION
# =========================
def get_collection():
    if not db.db:
        raise RuntimeError("Database belum connect")
    return db.db["payloads"]


# =========================
# SAVE PAYLOAD
# =========================
async def save_payload(user_id: int, data: str):
    try:
        col = get_collection()

        await col.update_one(
            {"_id": user_id},
            {"$set": {"data": data}},
            upsert=True
        )

        print("SAVE PAYLOAD:", user_id, data)

    except Exception as e:
        print("SAVE PAYLOAD ERROR:", e)


# =========================
# GET PAYLOAD
# =========================
async def get_payload(user_id: int):
    try:
        col = get_collection()

        doc = await col.find_one({"_id": user_id})

        if doc:
            print("GET PAYLOAD:", user_id, doc.get("data"))
            return doc.get("data")

        return None

    except Exception as e:
        print("GET PAYLOAD ERROR:", e)
        return None


# =========================
# CLEAR PAYLOAD
# =========================
async def clear_payload(user_id: int):
    try:
        col = get_collection()

        await col.delete_one({"_id": user_id})

        print("CLEAR PAYLOAD:", user_id)

    except Exception as e:
        print("CLEAR PAYLOAD ERROR:", e)