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

from typing import Any, Dict, Optional, Tuple

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


async def resolve_canonical_account_id(
    account_id: str,
    db: AsyncSession,
) -> Optional[str]:
    """Return the canonical `accounts.id` for an account or Clerk org identifier."""
    if not account_id or not hasattr(db, "execute"):
        return None

    try:
        result = await db.execute(
            text(
                """
                SELECT id
                FROM accounts
                WHERE id = :aid OR clerk_org_id = :aid
                LIMIT 1
                """
            ),
            {"aid": str(account_id)},
        )
    except Exception:
        return None

    row = result.first()
    if row and row[0]:
        return str(row[0])
    return None


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)
