import json
import asyncio
from uuid import UUID
from starlette.testclient import TestClient

from fmatch.saas.main import create_app
from fmatch.saas.auth import get_current_account
from fmatch.saas.api.v1.progress import get_redis


def test_results_returns_rows_and_results_alias():
    app = create_app()
    # stable account
    acct = UUID("11111111-1111-1111-1111-111111111111")
    app.dependency_overrides[get_current_account] = lambda: acct
    client = TestClient(app)

    # create a job
    payload = {
        "input": {"uri": "file://dummy.csv"},
        "intelligence": {"profile": "leads_to_accounts", "threshold": 0.75, "options": {}},
    }
    r = client.post("/api/v2/jobs/run", json=payload)
    assert r.status_code in (201, 200), r.text
    job_id = r.json()["job_id"]

    # prime Redis with a results payload (so we don’t need the worker)
    async def _prime():
        rc = await get_redis()
        data = {"results": [{"row": 1, "status": "Accepted"}], "pagination": {"total": 1}}
        await rc.set(f"job:{job_id}:results", json.dumps(data), ex=60)

    asyncio.get_event_loop().run_until_complete(_prime())

    # fetch results and assert aliasing
    r2 = client.get(f"/api/v2/jobs/{job_id}/results")
    assert r2.status_code == 200, r2.text
    body = r2.json()
    assert "rows" in body and "results" in body
    assert body["rows"] == body["results"]
    assert len(body["rows"]) == 1

