"""/api/stripe-activity HTTP layer: the auth gate, the owner-only gate, and
the parse roundtrip. Reuses the shared router fixtures."""

from tests.reporting.conftest import rpt_engine, rpt_url  # noqa: F401
from tests.routers.conftest import (  # noqa: F401
    as_adi,
    as_rian,
    client_factory,
)

PASTE = "\n".join(
    [
        "US$1,000.00", "-US$29.30", "US$970.70", "Charge", "Payments",
        "Invoice #2026087", "txn_abc", "Sep 4", "Sep 10",
    ]
)


def test_requires_auth(client):
    assert client.post("/api/stripe-activity/parse", json={"paste": ""}).status_code == 401


def test_non_owner_is_refused(as_adi):  # noqa: F811
    res = as_adi.post("/api/stripe-activity/parse", json={"paste": PASTE})
    assert res.status_code == 403
    assert res.json()["summary"] == "Only an owner can use the Stripe importer."


def test_owner_gets_rows_csv_and_stats(as_rian):  # noqa: F811
    res = as_rian.post("/api/stripe-activity/parse", json={"paste": PASTE})
    assert res.status_code == 200
    body = res.json()

    assert [r["description"] for r in body["rows"]] == [
        "Stripe Charge - Invoice #2026087",
        "Credit Card Fee",
    ]
    assert body["csv"].startswith("Date,Description,Amount")
    assert body["stats"]["transactions"] == 1
    assert body["stats"]["lines"] == 2
    assert body["stats"]["leftover_lines"] == 0
    assert body["stats"]["unknown_types"] == []
    # the derived date range is surfaced so a mis-inferred year is visible
    assert body["stats"]["first_date"] == body["stats"]["last_date"]
    assert body["stats"]["first_date"].endswith("-09-04")


def test_empty_paste_is_an_empty_result_not_an_error(as_rian):  # noqa: F811
    res = as_rian.post("/api/stripe-activity/parse", json={"paste": ""})
    assert res.status_code == 200
    assert res.json()["rows"] == []
    assert res.json()["stats"]["transactions"] == 0
