"""§22.4c — owner/admin mark-reviewed clears the flag; catalog unreviewed filter."""
from __future__ import annotations

from fastapi.testclient import TestClient

from test_propose_vertical import (  # noqa: F401
    app_with_fake_gitea, tmp_env, provision_user_row, sign_in_as,
)


def _seed_unreviewed_active(fake, slug="feat"):
    """Put an active+unreviewed entry on the meta repo main + cache."""
    from app import cache, entry as entry_mod
    body = entry_mod.serialize(entry_mod.Entry(
        slug=slug, title="Feat", state="active", unreviewed=True,
        owners=["ben"], proposed_by="ben",
    ))
    fake.files[("wiggleverse", "meta", "main", f"rfcs/{slug}.md")] = {"content": body, "sha": "s1"}
    cache._upsert_cached_rfc(entry_mod.parse(body), body_sha="s1")


def test_catalog_unreviewed_filter(app_with_fake_gitea):
    app, fake = app_with_fake_gitea
    with TestClient(app) as client:
        _seed_unreviewed_active(fake, "feat")
        from app import cache, entry as entry_mod
        ok = entry_mod.serialize(entry_mod.Entry(slug="ok", title="OK", state="active", owners=["ben"]))
        fake.files[("wiggleverse", "meta", "main", "rfcs/ok.md")] = {"content": ok, "sha": "s2"}
        cache._upsert_cached_rfc(entry_mod.parse(ok), body_sha="s2")
        r = client.get("/api/rfcs", params={"unreviewed": "true"})
        slugs = {i["slug"] for i in r.json()["items"]}
        assert slugs == {"feat"}


def test_mark_reviewed_clears_flag(app_with_fake_gitea):
    from app import db
    app, fake = app_with_fake_gitea
    with TestClient(app) as client:
        _seed_unreviewed_active(fake, "feat")
        provision_user_row(user_id=1, login="ben", role="owner")
        sign_in_as(client, user_id=1, gitea_login="ben", display_name="Ben", role="owner")
        r = client.post("/api/projects/default/rfcs/feat/mark-reviewed")
        assert r.status_code == 200
        row = db.conn().execute(
            "SELECT unreviewed, reviewed_at, reviewed_by FROM cached_rfcs WHERE slug='feat'"
        ).fetchone()
        assert row["unreviewed"] == 0
        assert row["reviewed_by"] == "ben"
        assert row["reviewed_at"]  # provenance stamped
        # git-side (§22.4a SLICE-4): the cleared flag now lands in the metadata
        # sidecar and the `.md` is lazy-migrated to a clean body-only file (INV-2).
        import yaml
        sidecar = fake.files[("wiggleverse", "meta", "main", "rfcs/feat.meta.yaml")]["content"]
        sc = yaml.safe_load(sidecar)
        assert not sc.get("unreviewed")          # cleared (omitted when False)
        assert sc.get("reviewed_by") == "ben"
        written = fake.files[("wiggleverse", "meta", "main", "rfcs/feat.md")]["content"]
        assert "---" not in written              # body-only, no frontmatter


def test_mark_reviewed_forbidden_for_non_superuser(app_with_fake_gitea):
    app, fake = app_with_fake_gitea
    with TestClient(app) as client:
        _seed_unreviewed_active(fake, "feat")
        provision_user_row(user_id=2, login="carol", role="contributor")
        sign_in_as(client, user_id=2, gitea_login="carol", display_name="Carol", role="contributor")
        r = client.post("/api/projects/default/rfcs/feat/mark-reviewed")
        assert r.status_code == 403
