"""
FastAPI dependencies for platform-level admin access.

Two tiers:
  require_platform_admin — user must be in admin_profiles
  require_super_admin    — user must have is_super_admin=True in admin_profiles

Usage:
    @router.get("/admin/schools")
    async def list_all_schools(admin=Depends(require_platform_admin)):
        ...

    @router.post("/admin/provision")
    async def provision(admin=Depends(require_super_admin)):
        ...
"""
from fastapi import Depends, HTTPException
from modules.auth.supabase_bearer import SupabaseBearer
from modules.database.supabase.utils.client import SupabaseServiceRoleClient


def _sb() -> SupabaseServiceRoleClient:
    return SupabaseServiceRoleClient()


async def require_platform_admin(
    credentials: dict = Depends(SupabaseBearer()),
) -> dict:
    """Require the caller to be a registered platform admin (in admin_profiles)."""
    user_id = credentials.get("sub")
    if not user_id:
        raise HTTPException(status_code=403, detail="Invalid token")
    try:
        sb = _sb()
        result = (
            sb.supabase.table("admin_profiles")
            .select("id,admin_role,is_super_admin")
            .eq("id", user_id)
            .single()
            .execute()
        )
        if not result.data:
            raise HTTPException(status_code=403, detail="Platform admin access required")
        return {**credentials, "admin_profile": result.data}
    except HTTPException:
        raise
    except Exception:
        raise HTTPException(status_code=403, detail="Platform admin access required")


async def require_super_admin(
    admin: dict = Depends(require_platform_admin),
) -> dict:
    """Require the caller to have is_super_admin=True."""
    if not admin.get("admin_profile", {}).get("is_super_admin"):
        raise HTTPException(status_code=403, detail="Super admin access required")
    return admin
