import pytest
from sqlalchemy import text


@pytest.mark.asyncio
async def test_tradeshow_import_idempotency_blocks_null_duplicates():
    # This test is dialect-aware: it verifies behavior only on Postgres.
    # On SQLite, NULLs in UNIQUE indexes are allowed; skip.
    from src.fmatch.saas.main import get_session

    async for db in get_session():
        dialect = db.bind.dialect.name if getattr(db, 'bind', None) else db.sync_engine.dialect.name
        if dialect != 'postgresql':
            pytest.skip('Idempotency functional unique index enforced only on Postgres')

        # Insert first row with NULL idem_key
        await db.execute(text("""
            INSERT INTO tradeshow_imports (id, account_id, content_hash, idem_key, status)
            VALUES ('imp1', 'acct1', 'hashA', NULL, 'accepted')
        """))
        await db.commit()

        # Second insert with same (account_id, content_hash) and NULL idem_key should fail
        with pytest.raises(Exception):
            await db.execute(text("""
                INSERT INTO tradeshow_imports (id, account_id, content_hash, idem_key, status)
                VALUES ('imp2', 'acct1', 'hashA', NULL, 'accepted')
            """))
            await db.commit()
        break

