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

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


class TestInsert:
    def test_insert_single_row_and_verify(self, cur):
        e = make_email("ins1")
        try:
            insert_user(cur, e, first_name="Alice", last_name="Live")
            cur.execute(
                f"SELECT first_name, last_name, email FROM {TABLE} WHERE email = '{e}'"
            )
            rows = cur.fetchall()
            assert len(rows) == 1
            assert rows[0][0] == "Alice"
            assert rows[0][1] == "Live"
            assert rows[0][2] == e
        finally:
            cleanup(cur, e)

    def test_insert_multiple_rows_independently(self, cur):
        emails = [make_email(f"insmulti{i}") for i in range(3)]
        try:
            for i, e in enumerate(emails):
                insert_user(cur, e, first_name=f"Multi{i}", company="MultiTestCo")
            for e in emails:
                cur.execute(f"SELECT email FROM {TABLE} WHERE email = '{e}'")
                assert len(cur.fetchall()) == 1, f"Expected inserted row for {e}"
        finally:
            cleanup(cur, *emails)

    def test_insert_sets_default_is_active_true(self, cur):
        e = make_email("insactive")
        try:
            insert_user(cur, e)
            cur.execute(f"SELECT is_active FROM {TABLE} WHERE email = '{e}'")
            row = cur.fetchone()
            assert row is not None
            assert row[0] is True
        finally:
            cleanup(cur, e)

    def test_insert_via_executemany_batch(self, cur):
        """Two rows in a single /batch call via executemany with multiple param sets."""
        emails = [make_email(f"insmany{i}") for i in range(2)]
        try:
            cur.executemany(
                f"INSERT INTO {TABLE} "
                "(first_name, last_name, email, phone, date_of_birth, gender, "
                "country, city, address, occupation, company) VALUES "
                "(@fn, @ln, @em, @ph, '1995-06-15', @gn, @co, @ci, @ad, @oc, @cm)",
                [
                    {
                        "@fn": f"Batch{i}", "@ln": "User", "@em": e,
                        "@ph": f"+1-555-30{i}0",
                        "@gn": "Other", "@co": "Canada", "@ci": "Toronto",
                        "@ad": "3 Batch Ave", "@oc": "Engineer", "@cm": "BatchCo",
                    }
                    for i, e in enumerate(emails)
                ],
            )
            for e in emails:
                cur.execute(f"SELECT email FROM {TABLE} WHERE email = '{e}'")
                assert len(cur.fetchall()) == 1
        finally:
            cleanup(cur, *emails)
