"""/api/cc HTTP layer: auth gate, owner-only enforcement, and the
structured-error translation. Runs against the shared reporting scratch
DB (migrated fixture graph); the owner roundtrip cleans up after itself
so the shared state is left untouched."""

# reuse the router + reporting scratch-DB fixtures (established pattern)
from tests.reporting.conftest import rpt_engine, rpt_url  # noqa: F401
from tests.routers.conftest import (  # noqa: F401
    as_adi,
    as_rian,
    client_factory,
)


def test_batches_requires_auth(client):
    assert client.get("/api/cc/batches").status_code == 401


def test_non_owner_gets_owner_only(as_adi):  # noqa: F811
    listed = as_adi.get("/api/cc/batches")
    assert listed.status_code == 403
    assert listed.json()["summary"] == "Owner only."

    created = as_adi.post("/api/cc/batches", json={"name": "sneaky"})
    assert created.status_code == 403
    assert created.json()["summary"] == "Only an owner can create expense batches."

    rules = as_adi.get("/api/cc/rules")
    assert rules.status_code == 403


def test_owner_roundtrip_and_structured_errors(as_rian):  # noqa: F811
    batch_id = None
    try:
        created = as_rian.post("/api/cc/batches", json={"name": "M7 router smoke"})
        assert created.status_code == 200
        batch_id = created.json()["row"]["id"]

        # appears in the list
        rows = as_rian.get("/api/cc/batches").json()["rows"]
        assert any(r["id"] == batch_id for r in rows)

        # append + detail
        paste = "May 20, 2026\tFACEBK *X\t$7.15\t\t$100.00\t"
        appended = as_rian.post(f"/api/cc/batches/{batch_id}/lines", json={"paste": paste})
        assert appended.status_code == 200
        assert appended.json()["added"] == 1

        detail = as_rian.get(f"/api/cc/batches/{batch_id}")
        assert detail.status_code == 200
        assert detail.json()["totals"]["lines"] == 1
        assert "project_options" in detail.json()

        # structured error: empty paste -> 422 + summary
        empty = as_rian.post(f"/api/cc/batches/{batch_id}/lines", json={"paste": ""})
        assert empty.status_code == 422
        assert empty.json()["summary"] == "Paste some lines first."

        # paste block (nothing assigned yet)
        block = as_rian.get(f"/api/cc/batches/{batch_id}/paste-block")
        assert block.status_code == 200
        assert block.json()["line_count"] == 0

        # rules payload
        assert as_rian.get("/api/cc/rules").status_code == 200
    finally:
        if batch_id:
            as_rian.delete(f"/api/cc/batches/{batch_id}")
