import pytest

import ydb
from ydb.aio.query.transaction import QueryTxContext
from ydb.query.transaction import QueryTxStateEnum


class TestAsyncQueryTransaction:
    @pytest.mark.asyncio
    async def test_tx_begin(self, tx: QueryTxContext):
        assert tx.tx_id is None

        await tx.begin()
        assert tx.tx_id is not None

    @pytest.mark.asyncio
    async def test_tx_allow_double_commit(self, tx: QueryTxContext):
        await tx.begin()
        await tx.commit()
        await tx.commit()

    @pytest.mark.asyncio
    async def test_tx_allow_double_rollback(self, tx: QueryTxContext):
        await tx.begin()
        await tx.rollback()
        await tx.rollback()

    @pytest.mark.asyncio
    async def test_tx_commit_before_begin(self, tx: QueryTxContext):
        await tx.commit()
        assert tx._tx_state._state == QueryTxStateEnum.COMMITTED

    @pytest.mark.asyncio
    async def test_tx_rollback_before_begin(self, tx: QueryTxContext):
        await tx.rollback()
        assert tx._tx_state._state == QueryTxStateEnum.ROLLBACKED

    @pytest.mark.asyncio
    async def test_tx_first_execute_begins_tx(self, tx: QueryTxContext):
        await tx.execute("select 1;")
        await tx.commit()

    @pytest.mark.asyncio
    async def test_interactive_tx_commit(self, tx: QueryTxContext):
        await tx.execute("select 1;", commit_tx=True)
        with pytest.raises(RuntimeError):
            await tx.execute("select 1;")

    @pytest.mark.asyncio
    async def test_tx_execute_raises_after_commit(self, tx: QueryTxContext):
        await tx.begin()
        await tx.commit()
        with pytest.raises(RuntimeError):
            await tx.execute("select 1;")

    @pytest.mark.asyncio
    async def test_tx_execute_raises_after_rollback(self, tx: QueryTxContext):
        await tx.begin()
        await tx.rollback()
        with pytest.raises(RuntimeError):
            await tx.execute("select 1;")

    @pytest.mark.asyncio
    async def test_context_manager_rollbacks_tx(self, tx: QueryTxContext):
        async with tx:
            await tx.begin()

        assert tx._tx_state._state == QueryTxStateEnum.ROLLBACKED

    @pytest.mark.asyncio
    async def test_context_manager_normal_flow(self, tx: QueryTxContext):
        async with tx:
            await tx.begin()
            await tx.execute("select 1;")
            await tx.commit()

        assert tx._tx_state._state == QueryTxStateEnum.COMMITTED

    @pytest.mark.asyncio
    async def test_context_manager_does_not_hide_exceptions(self, tx: QueryTxContext):
        class CustomException(Exception):
            pass

        with pytest.raises(CustomException):
            async with tx:
                raise CustomException()

    @pytest.mark.asyncio
    async def test_execute_as_context_manager(self, tx: QueryTxContext):
        await tx.begin()

        async with await tx.execute("select 1;") as results:
            res = [result_set async for result_set in results]

        assert len(res) == 1

    @pytest.mark.asyncio
    async def test_execute_two_results(self, tx: QueryTxContext):
        await tx.begin()
        counter = 0
        res = []

        async with await tx.execute("select 1; select 2") as results:
            async for result_set in results:
                counter += 1
                if len(result_set.rows) > 0:
                    res.append(list(result_set.rows[0].values()))

        assert res == [[1], [2]]
        assert counter == 2

    @pytest.mark.asyncio
    @pytest.mark.usefixtures("ydb_terminates_streams_with_unavailable")
    async def test_terminated_stream_raises_ydb_error(self, tx: QueryTxContext):
        await tx.begin()

        with pytest.raises(ydb.Unavailable):
            async with await tx.execute("select 1") as results:
                async for _ in results:
                    pass

    @pytest.mark.asyncio
    async def test_rollback_after_tli_aborted_is_safe(self, pool, table_path: str):
        # Given: a row in a table
        table_ref = f"`{table_path}`"
        await pool.execute_with_retries(f"UPSERT INTO {table_ref} (id, i64Val) VALUES (1, 0);")

        # When: two concurrent transactions try to modify this row.
        async with pool.checkout() as session1, pool.checkout() as session2:
            tx1 = session1.transaction()
            tx2 = session2.transaction()

            async with await tx1.execute(f"SELECT i64Val FROM {table_ref} WHERE id = 1;") as _:
                pass

            async with await tx2.execute(f"UPSERT INTO {table_ref} (id, i64Val) VALUES (1, 1);", commit_tx=True) as _:
                pass

            async with await tx1.execute(f"UPSERT INTO {table_ref} (id, i64Val) VALUES (1, 2);") as _:
                pass
            with pytest.raises(ydb.Aborted):
                await tx1.commit()  # receive TLI here

            # Then: rollback (as a handling of Aborted exception) must be successful.
            await tx1.rollback()
