"""
Supabase admin client (singleton).

⚠️ SECURITY WARNING ⚠️
This client uses SUPABASE_SECRET_KEY which BYPASSES Row Level Security.
- NEVER expose this client or its key to the frontend.
- NEVER log the key or commit it to Git.
- Every endpoint using this client is responsible for its own authorization
  checks BEFORE calling Supabase (verify JWT, check user role, etc.).

Usage:
    from app.core.supabase_client import supabase

    result = supabase.table("profiles").select("*").eq("id", user_id).execute()
"""
from supabase import create_client, Client
from app.core.config import settings


def _build_admin_client() -> Client:
    """
    Build the admin Supabase client at module load time.
    Fails fast if credentials are missing (better than silent failure later).
    """
    if not settings.SUPABASE_URL:
        raise RuntimeError(
            "SUPABASE_URL is not set in .env. Cannot initialize Supabase client."
        )
    if not settings.SUPABASE_SECRET_KEY:
        raise RuntimeError(
            "SUPABASE_SECRET_KEY is not set in .env. Cannot initialize Supabase client."
        )

    return create_client(
        supabase_url=settings.SUPABASE_URL,
        supabase_key=settings.SUPABASE_SECRET_KEY,
    )


# Singleton instance — created once at module import, shared everywhere
supabase: Client = _build_admin_client()
