"""Shared mattermost-lts test helpers.

mattermost lets the FIRST user be created unauthenticated (and makes them system admin); after that,
open signups are disabled (`api.user.create_user.no_open_server`). Several functional tests share one
per-run deployment (the custom tier), so they cannot each create "the first user." Instead they all
bootstrap ONE deterministic admin: whichever test runs first creates it (201, as the first user); the
rest log in as the same admin. Subsequent (non-first) users are created via the admin token, which
works regardless of the open-signup setting.
"""

from __future__ import annotations

import os
import sys

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

ADMIN_EMAIL = "ccci-admin@ccci.example.com"
ADMIN_USERNAME = "ccciadmin"
ADMIN_PW = "Ccci-Test-Pw-2026!"


def bearer(token: str) -> dict[str, str]:
    return {"Authorization": f"Bearer {token}"}


def bootstrap_admin(base: str) -> str:
    """Return a system-admin session token for the shared deployment.

    Create the deterministic admin as the first user if the server is fresh (201); otherwise it
    already exists (400/403) — log in as it. Either way we end with a valid admin token. RAISES if
    neither create nor login yields a usable session (a genuinely broken auth path)."""
    # Try to create the first user (unauthenticated; only succeeds on a fresh server).
    harness_http.http_post(
        f"{base}/users",
        data={"email": ADMIN_EMAIL, "username": ADMIN_USERNAME, "password": ADMIN_PW},
        timeout=30,
    )
    # Whether or not creation succeeded (it 4xxs if the admin already exists / signups closed), log in.
    status, _, hdrs = harness_http.post_with_headers(
        f"{base}/users/login", data={"login_id": ADMIN_EMAIL, "password": ADMIN_PW}, timeout=30
    )
    assert status == 200, f"admin login failed: HTTP {status}"
    token = hdrs.get("Token") or hdrs.get("token")
    assert token, f"admin login returned no Token header; headers={list(hdrs.keys())}"
    return token
