import io
import pandas as pd
import pytest
from fastapi import UploadFile

from src.fmatch.saas.services.tradeshow_service import TradeshowService
from src.fmatch.saas.workers.tradeshow_worker import TradeshowWorker


@pytest.mark.asyncio
async def test_tradeshow_commit_and_worker(db_session=None):
    # Prepare a tiny CSV with simple duplicates to produce matches
    df = pd.DataFrame([
        {"Id": "1", "Email": "a@example.com", "Name": "Acme"},
        {"Id": "2", "Email": "a@example.com", "Name": "Acme Inc"},
    ])
    content = df.to_csv(index=False).encode()
    up = UploadFile(filename="sample.csv", file=io.BytesIO(content), content_type="text/csv")

    # Use in-memory test DB via app overrides
    from src.fmatch.saas.main import get_session
    async for db in get_session():
        svc = TradeshowService(db=db)
        res = await svc.accept_import(up, idem_key=None, account_id="acctA")
        import_id = res["import_id"]
        commit = await svc.commit(import_id, account_id="acctA")
        job_id = commit["job_id"]

        # Run worker inline to avoid race
        worker = TradeshowWorker(db=db, storage=svc.storage)
        await worker.run_job(job_id)

        report = await svc.report(job_id)
        assert report["matched_count"] >= 1
        assert "summary" in report
        break

