"""
NAS API Session Management
Handle session ID persistence via Supabase.
"""

from datetime import datetime, timezone
from typing import Optional

from .config import logger
from ..supabase_service import get_supabase_client

SESSION_ID = "nas_filestation"


def save_sid(sid: str) -> None:
    """Save session ID to Supabase for persistence across requests."""
    try:
        supabase = get_supabase_client()
        supabase.table("sessions").upsert({
            "id": SESSION_ID,
            "data": {"sid": sid},
            "last_login": datetime.now(timezone.utc).isoformat(),
            "updated_at": datetime.now(timezone.utc).isoformat()
        }).execute()
        logger.debug(f"Session ID saved to Supabase: {sid[:8]}...")
    except Exception as e:
        logger.error(f"Error saving session ID to Supabase: {e}")


def load_sid() -> Optional[str]:
    """Load session ID from Supabase if it exists."""
    try:
        supabase = get_supabase_client()
        result = supabase.table("sessions").select(
            "data").eq("id", SESSION_ID).single().execute()
        if result.data and isinstance(result.data, dict):
            data = result.data.get("data")
            if isinstance(data, dict):
                sid = data.get("sid")
                if isinstance(sid, str) and sid:
                    logger.debug(
                        f"Session ID loaded from Supabase: {sid[:8]}...")
                    return sid
    except Exception as e:
        logger.error(f"Error loading session ID from Supabase: {e}")
    return None
