from __future__ import annotations
from sqlalchemy import select
from sqlalchemy.dialects.mysql import insert as mysql_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.plugins.pos_sync.models import PosCatalogueRevision


async def get_revision(db: AsyncSession, tenant_id: int) -> int:
    row = (await db.execute(
        select(PosCatalogueRevision.revision).where(PosCatalogueRevision.tenant_id == tenant_id)
    )).scalar_one_or_none()
    return int(row or 0)


async def bump_revision(db: AsyncSession, tenant_id: int) -> None:
    """Atomically increment the tenant's catalogue revision. Caller's transaction commits."""
    stmt = mysql_insert(PosCatalogueRevision).values(tenant_id=tenant_id, revision=1)
    stmt = stmt.on_duplicate_key_update(revision=PosCatalogueRevision.revision + 1)
    await db.execute(stmt)
