import json
import os

STORE_FILE = "data/pending_approvals.json"


def load_pending():
    if not os.path.exists(STORE_FILE):
        return {}
    with open(STORE_FILE, "r", encoding="utf-8") as f:
        try:
            raw = json.load(f)
            # key di JSON adalah string, konversi ke int
            return {int(k): v for k, v in raw.items()}
        except Exception:
            return {}


def save_pending(data):
    with open(STORE_FILE, "w", encoding="utf-8") as f:
        json.dump(
            {str(k): v for k, v in data.items()},
            f,
            indent=2,
            ensure_ascii=False
        )


def set_pending(user_id: int, entry: dict):
    data = load_pending()
    data[user_id] = entry
    save_pending(data)


def get_pending(user_id: int):
    data = load_pending()
    return data.get(user_id, {})


def delete_pending(user_id: int):
    data = load_pending()
    if user_id in data:
        del data[user_id]
        save_pending(data)
