# retoor <retoor@molodetz.nl>

import time

import requests

from tests.conftest import BASE_URL

_counter = [0]
JSON = {"Accept": "application/json"}


def _signup(password="secret123"):
    _counter[0] += 1
    name = f"tgpair{int(time.time() * 1000)}{_counter[0]}"
    session = requests.Session()
    session.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": password,
            "confirm_password": password,
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    return session, name


def test_owner_requests_pairing_code(app_server):
    session, name = _signup()
    resp = session.post(
        f"{BASE_URL}/profile/{name}/telegram",
        data={"action": "request"},
        headers=JSON,
    )
    assert resp.status_code == 200
    body = resp.json()
    assert body["ok"] is True
    assert body["code"].isdigit() and len(body["code"]) == 4
    assert body["ttl_minutes"] >= 1


def test_unpair_returns_ok(app_server):
    session, name = _signup()
    resp = session.post(
        f"{BASE_URL}/profile/{name}/telegram",
        data={"action": "unpair"},
        headers=JSON,
    )
    assert resp.status_code == 200
    assert resp.json()["paired"] is False


def test_other_user_cannot_request_code(app_server):
    _, target = _signup()
    attacker, _ = _signup()
    resp = attacker.post(
        f"{BASE_URL}/profile/{target}/telegram",
        data={"action": "request"},
        headers=JSON,
        allow_redirects=False,
    )
    assert resp.status_code == 403


def test_request_without_json_redirects_to_profile(app_server):
    session, name = _signup()
    resp = session.post(
        f"{BASE_URL}/profile/{name}/telegram",
        data={"action": "request"},
        allow_redirects=False,
    )
    assert resp.status_code == 302
    assert resp.headers["location"] == f"/profile/{name}"


def test_unpair_without_json_redirects_to_profile(app_server):
    session, name = _signup()
    resp = session.post(
        f"{BASE_URL}/profile/{name}/telegram",
        data={"action": "unpair"},
        allow_redirects=False,
    )
    assert resp.status_code == 302
    assert resp.headers["location"] == f"/profile/{name}"
