"""Shared helpers for resolving account identity in v2 APIs."""

from typing import Any, Dict, Tuple

from fastapi import HTTPException
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession


async def resolve_account_id(identity: Dict[str, Any], db: AsyncSession) -> Tuple[str, str]:
    """Return (canonical_account_id, clerk_org_id) for the request identity."""
    org_id = identity.get("org_id") or identity.get("account_id")
    if not org_id:
        raise HTTPException(400, "No organization context in token")

    result = await db.execute(
        text("SELECT id, clerk_org_id FROM accounts WHERE id = :oid OR clerk_org_id = :oid"),
        {"oid": str(org_id)},
    )
    row = result.first()
    if row:
        account_id = str(row[0])
        clerk_org_id = str(row[1]) if row[1] else str(org_id)
        return account_id, clerk_org_id

    return str(org_id), str(org_id)
