"""SELECT tests against the live CData Connect AI environment."""

from tests.integration_live.helpers import TABLE, cleanup, insert_user, make_email


class TestSelect:
    def test_select_returns_list(self, cur):
        cur.execute(f"SELECT id, first_name, last_name, email FROM {TABLE} LIMIT 5")
        rows = cur.fetchall()
        assert isinstance(rows, list)

    def test_description_exposes_column_metadata(self, cur):
        cur.execute(f"SELECT id, first_name, email, is_active FROM {TABLE} LIMIT 1")
        cur.fetchall()
        assert cur.description is not None
        col_names = [d[0].lower() for d in cur.description]
        for col in ("id", "first_name", "email", "is_active"):
            assert col in col_names, f"Expected column '{col}' in description"

    def test_select_with_where_filter(self, cur):
        e = make_email("selflt")
        try:
            insert_user(cur, e, first_name="FilterMe")
            cur.execute(f"SELECT first_name, email FROM {TABLE} WHERE email = '{e}'")
            rows = cur.fetchall()
            assert len(rows) == 1
            assert rows[0][0] == "FilterMe"
            assert rows[0][1] == e
        finally:
            cleanup(cur, e)

    def test_select_order_by_id_ascending(self, cur):
        cur.execute(f"SELECT id FROM {TABLE} ORDER BY id ASC LIMIT 10")
        ids = [r[0] for r in cur.fetchall()]
        assert ids == sorted(ids), "Rows should be in ascending id order"

    def test_select_count_returns_integer(self, cur):
        cur.execute(f"SELECT COUNT(*) FROM {TABLE}")
        rows = cur.fetchall()
        assert len(rows) == 1
        assert isinstance(rows[0][0], int)
        assert rows[0][0] >= 0

    def test_fetchone_returns_single_row(self, cur):
        cur.execute(f"SELECT id, first_name FROM {TABLE} LIMIT 5")
        row = cur.fetchone()
        assert row is not None
        assert len(row) == 2

    def test_fetchmany_respects_size(self, cur):
        cur.execute(f"SELECT id FROM {TABLE} LIMIT 10")
        rows = cur.fetchmany(3)
        assert len(rows) <= 3

    def test_iterate_cursor(self, cur):
        e = make_email("selitr")
        try:
            insert_user(cur, e)
            cur.execute(f"SELECT email FROM {TABLE} WHERE email = '{e}'")
            collected = list(cur)
            assert any(r[0] == e for r in collected)
        finally:
            cleanup(cur, e)
