"""mattermost-lts — Q4.5 recipe-specific functional test (plan §4.3: "create the app's primary
object — a message — and read it back").

Exercises mattermost's core function end-to-end against the live per-run deploy, via the REST API:
  1. Bootstrap the FIRST user (a fresh mattermost server lets the first user be created unauthenticated
     and makes them system admin).
  2. Log in → capture the session token from the `Token` response header.
  3. Create a team, then an open channel in it.
  4. POST a message (a unique marker) to the channel.
  5. GET the post back by id and assert the message text round-trips intact.

NOT health-only: a mattermost whose DB/API/posting path is broken fails here even though `/` and
`/api/v4/system/ping` return 200. The marker is unique per run so a stale/echoed response can't pass.
"""

from __future__ import annotations

import os
import sys
import uuid

sys.path.insert(0, os.path.dirname(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
import _mm  # noqa: E402
from harness import http as harness_http  # noqa: E402


def test_create_message_roundtrip(live_app):
    base = f"https://{live_app}/api/v4"
    uniq = uuid.uuid4().hex[:10]

    # 1-2) Bootstrap the shared system admin (first user on a fresh server, else log in as it).
    # mattermost allows only ONE unauthenticated first-user creation, and several functional tests
    # share this deployment — so all bootstrap the same deterministic admin (see _mm.bootstrap_admin).
    auth = _mm.bearer(_mm.bootstrap_admin(base))

    # 3) Create a team, then an open channel in it.
    status, team = harness_http.http_post(
        f"{base}/teams",
        data={"name": f"t{uniq}", "display_name": f"ccci {uniq}", "type": "O"},
        headers=auth,
        timeout=30,
    )
    assert status in (200, 201) and isinstance(team, dict) and team.get("id"), (
        f"team creation failed: HTTP {status}, body={team!r}"
    )
    status, chan = harness_http.http_post(
        f"{base}/channels",
        data={
            "team_id": team["id"],
            "name": f"c{uniq}",
            "display_name": f"chan {uniq}",
            "type": "O",
        },
        headers=auth,
        timeout=30,
    )
    assert status in (200, 201) and isinstance(chan, dict) and chan.get("id"), (
        f"channel creation failed: HTTP {status}, body={chan!r}"
    )

    # 4) POST a unique marker message.
    marker = f"ccci-marker-{uniq}-roundtrip"
    status, post = harness_http.http_post(
        f"{base}/posts",
        data={"channel_id": chan["id"], "message": marker},
        headers=auth,
        timeout=30,
    )
    assert status in (200, 201) and isinstance(post, dict) and post.get("id"), (
        f"post creation failed: HTTP {status}, body={post!r}"
    )

    # 5) Read it back by id and assert the message survived the round-trip.
    status, got = harness_http.http_get(f"{base}/posts/{post['id']}", headers=auth, timeout=30)
    assert status == 200 and isinstance(got, dict), f"read-back failed: HTTP {status}, body={got!r}"
    assert got.get("message") == marker, (
        f"message did not round-trip: sent {marker!r}, got {got.get('message')!r}"
    )
