from grantflow.tests.critic_bulk_status_helpers import client, set_bulk_critic_job


def test_status_critic_bulk_status_updates_support_filters_and_apply_all():
    job_id = "critic-findings-bulk-1"
    set_bulk_critic_job(job_id)

    no_selector_resp = client.post(
        f"/status/{job_id}/critic/findings/bulk-status",
        json={"next_status": "resolved"},
    )
    assert no_selector_resp.status_code == 400
    assert "selector" in str(no_selector_resp.json().get("detail") or "")

    filtered_resp = client.post(
        f"/status/{job_id}/critic/findings/bulk-status",
        headers={"X-Actor": "bulk_reviewer"},
        json={
            "next_status": "acknowledged",
            "section": "toc",
            "severity": "high",
            "finding_status": "open",
        },
    )
    assert filtered_resp.status_code == 200
    filtered_body = filtered_resp.json()
    assert filtered_body["requested_status"] == "acknowledged"
    assert filtered_body["actor"] == "bulk_reviewer"
    assert filtered_body["matched_count"] == 1
    assert filtered_body["changed_count"] == 1
    assert filtered_body["unchanged_count"] == 0
    assert filtered_body["filters"]["section"] == "toc"
    assert filtered_body["filters"]["severity"] == "high"
    assert filtered_body["filters"]["finding_status"] == "open"
    assert filtered_body["updated_findings"][0]["finding_id"] == "bulk-f1"
    assert filtered_body["updated_findings"][0]["status"] == "acknowledged"

    id_filtered_resp = client.post(
        f"/status/{job_id}/critic/findings/bulk-status",
        json={
            "next_status": "resolved",
            "finding_ids": ["bulk-f2", "bulk-f404"],
        },
    )
    assert id_filtered_resp.status_code == 200
    id_filtered_body = id_filtered_resp.json()
    assert id_filtered_body["matched_count"] == 1
    assert id_filtered_body["changed_count"] == 1
    assert id_filtered_body["not_found_finding_ids"] == ["bulk-f404"]
    assert id_filtered_body["updated_findings"][0]["finding_id"] == "bulk-f2"
    assert id_filtered_body["updated_findings"][0]["status"] == "resolved"

    apply_all_resp = client.post(
        f"/status/{job_id}/critic/findings/bulk-status",
        json={"next_status": "resolved", "apply_to_all": True},
    )
    assert apply_all_resp.status_code == 200
    apply_all_body = apply_all_resp.json()
    assert apply_all_body["matched_count"] == 3
    assert apply_all_body["changed_count"] >= 1
    assert apply_all_body["filters"]["apply_to_all"] is True

    critic_resp = client.get(f"/status/{job_id}/critic")
    assert critic_resp.status_code == 200
    critic_flaws = critic_resp.json()["fatal_flaws"]
    assert len(critic_flaws) == 3
    assert all(str(item.get("status") or "") == "resolved" for item in critic_flaws)
