from typing import Any, Dict, List, Optional, cast

from app.core.supabase import get_supabase


def get_session(user_id: str, session_token: str) -> Optional[Dict[str, Any]]:
    supabase = get_supabase()
    result = (
        supabase.table("user_sessions")
        .select("*")
        .eq("user_id", user_id)
        .eq("session_token", session_token)
        .execute()
    )
    data = cast(List[Dict[str, Any]], result.data or [])
    return data[0] if data else None


def delete_sessions(user_id: str) -> None:
    supabase = get_supabase()
    supabase.table("user_sessions").delete().eq("user_id", user_id).execute()


def create_session(user_id: str, session_token: str, device_info: Optional[str] = None) -> List[Dict[str, Any]]:
    supabase = get_supabase()
    result = supabase.table("user_sessions").insert({
        "user_id": user_id,
        "session_token": session_token,
        "device_info": device_info,
    }).execute()
    return cast(List[Dict[str, Any]], result.data or [])
