# grantflow/tests/test_integration_security.py

from fastapi.testclient import TestClient

from grantflow.api.app import app

client = TestClient(app)


def test_generate_requires_api_key_when_configured(monkeypatch):
    monkeypatch.setenv("GRANTFLOW_API_KEY", "test-secret")

    preflight_response = client.post("/generate/preflight", json={"donor_id": "usaid"})
    assert preflight_response.status_code == 401

    preflight_response = client.post(
        "/generate/preflight",
        json={"donor_id": "usaid"},
        headers={"X-API-Key": "test-secret"},
    )
    assert preflight_response.status_code == 200
    assert preflight_response.json()["donor_id"] == "usaid"

    payload = {
        "donor_id": "usaid",
        "input_context": {"project": "Public Health", "country": "Kenya"},
        "llm_mode": False,
        "hitl_enabled": False,
    }

    response = client.post("/generate", json=payload)
    assert response.status_code == 401

    response = client.post("/generate", json=payload, headers={"X-API-Key": "test-secret"})
    assert response.status_code == 200
    assert response.json()["status"] == "accepted"

    from_preset_payload = {
        "preset_key": "usaid_gov_ai_kazakhstan",
        "preset_type": "legacy",
        "llm_mode": False,
        "hitl_enabled": False,
        "architect_rag_enabled": False,
        "strict_preflight": False,
    }
    from_preset_unauth = client.post("/generate/from-preset", json=from_preset_payload)
    assert from_preset_unauth.status_code == 401

    from_preset_auth = client.post(
        "/generate/from-preset",
        json=from_preset_payload,
        headers={"X-API-Key": "test-secret"},
    )
    assert from_preset_auth.status_code == 200
    assert from_preset_auth.json()["status"] == "accepted"

    from_preset_batch_payload = {
        "items": [
            {
                "preset_key": "usaid_gov_ai_kazakhstan",
                "preset_type": "legacy",
                "llm_mode": False,
                "hitl_enabled": False,
                "architect_rag_enabled": False,
                "strict_preflight": False,
            }
        ]
    }
    from_preset_batch_unauth = client.post("/generate/from-preset/batch", json=from_preset_batch_payload)
    assert from_preset_batch_unauth.status_code == 401

    from_preset_batch_auth = client.post(
        "/generate/from-preset/batch",
        json=from_preset_batch_payload,
        headers={"X-API-Key": "test-secret"},
    )
    assert from_preset_batch_auth.status_code == 200
    assert from_preset_batch_auth.json()["status"] == "accepted"
