"""Atomic per-tenant sequence counters — backs a Task's generate_sequence
node. A single INSERT ... ON CONFLICT DO UPDATE ... RETURNING is one atomic
statement, so concurrent callers incrementing the same key never race (no
separate read-then-write, no explicit row lock needed)."""

import uuid

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


async def next_sequence_value(db: AsyncSession, tenant_id: uuid.UUID, key: str) -> int:
    result = await db.execute(
        text(
            """
            INSERT INTO sequence_counters (tenant_id, key, current_value)
            VALUES (:tenant_id, :key, 1)
            ON CONFLICT (tenant_id, key)
            DO UPDATE SET current_value = sequence_counters.current_value + 1, updated_at = now()
            RETURNING current_value
            """
        ),
        {"tenant_id": str(tenant_id), "key": key},
    )
    return result.scalar_one()
