from typing import Generator, Optional, Dict, Any
from fastapi import Request
from app.db.session import get_conn

def _set_config(cur, key: str, value: str) -> None:
    cur.execute("SELECT set_config(%s, %s, false);", (key, value))

def db_tx(request: Request) -> Generator[Dict[str, Any], None, None]:
    """
    Egységes DB tranzakció + session context:
    BEGIN
      set_config(app.tenant_org_id, app.account_id, app.is_platform_admin)
    COMMIT/ROLLBACK
    """
    conn = get_conn()
    try:
        cur = conn.cursor()
        cur.execute("BEGIN;")

        claims: Optional[dict] = getattr(request.state, "claims", None)
        if claims:
            org_id = claims.get("org_id") or ""
            account_id = claims.get("sub") or ""
            is_platform_admin = claims.get("is_platform_admin", False)

            # Fontos: set_config stringeket vár
            _set_config(cur, "app.tenant_org_id", str(org_id))
            _set_config(cur, "app.account_id", str(account_id))
            _set_config(cur, "app.is_platform_admin", "true" if is_platform_admin else "false")

        yield {"conn": conn, "cur": cur}

        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()
