"""Security gate: the two bulk-text ingress paths are size-bounded
(M8 hardening). An unbounded upload/paste is a memory-exhaustion DoS
lever; both the CSV import and the CC statement paste cap their input.
"""

import pytest

from app.services.cc.service import MAX_PASTE_BYTES
from app.services.imports.errors import ImportsError
from app.services.imports.staging import MAX_UPLOAD_BYTES, stage_upload

# migrated scratch DB + real actors
from tests.reporting.conftest import rian, rpt_engine, rpt_session, rpt_url  # noqa: F401
from tests.routers.conftest import as_rian, client_factory  # noqa: F401


def test_csv_upload_rejects_oversized(rpt_session, rian):  # noqa: F811
    """>25 MB CSV -> FILE_TOO_LARGE before any parse/commit (T-IMP-005)."""
    oversized = b"x" * (MAX_UPLOAD_BYTES + 1)
    with pytest.raises(ImportsError) as exc:
        stage_upload(rpt_session, rian, filename="huge.csv", data=oversized)
    assert exc.value.code == "FILE_TOO_LARGE"
    assert exc.value.status == 400


def test_cc_paste_rejects_oversized(as_rian):  # noqa: F811
    """>1 MB statement paste -> PASTE_TOO_LARGE (M8 new bound)."""
    made = as_rian.post("/api/cc/batches", json={"name": "Size guard batch"})
    assert made.status_code == 200, made.text
    batch_id = made.json()["row"]["id"]
    try:
        huge = "a\t" * (MAX_PASTE_BYTES // 2 + 10)  # > MAX_PASTE_BYTES bytes
        resp = as_rian.post(
            f"/api/cc/batches/{batch_id}/lines", json={"paste": huge}
        )
        assert resp.status_code == 413, resp.text
        assert resp.json()["error_code"] == "PASTE_TOO_LARGE"
    finally:
        as_rian.delete(f"/api/cc/batches/{batch_id}")
