# /var/www/html/bot/app/services/subscription_service.py
from typing import Optional
from app.services.supabase_service import get_client, logger

supabase = get_client()

def is_subscribed(chat_id: int) -> bool:
    try:
        res = supabase.table("subscribers").select("chat_id").eq("chat_id", chat_id).limit(1).execute()
        return bool(res.data)
    except Exception as e:
        logger.exception(f"is_subscribed error: {e}")
        return False

async def toggle_subscription(chat_id: int) -> bool:
    """
    구독 상태를 토글하고, 최종 상태(True=구독중/False=해지)를 리턴
    (간단화를 위해 async로 선언했지만 내부는 동기 I/O)
    """
    try:
        if is_subscribed(chat_id):
            supabase.table("subscribers").delete().eq("chat_id", chat_id).execute()
            logger.info(f"unsubscribe: {chat_id}")
            return False
        else:
            supabase.table("subscribers").insert({"chat_id": chat_id}).execute()
            logger.info(f"subscribe: {chat_id}")
            return True
    except Exception as e:
        logger.exception(f"toggle_subscription error: {e}")
        # 에러시 상태 변화 없다고 가정하고 현재 상태 리턴
        return is_subscribed(chat_id)
