"""微信登录 M2 测试:conflict_ticket 令牌、继续绑定(attach/只登入)、换绑(建号+软删+30天限)。

沿用 tests/test_wechat_login.py 风格:HTTP 走 client;微信 code→openid 用 monkeypatch;
短信走 SMS_MOCK(任意 6 位过)。数据变更用"再走一遍 wechat-login 看 openid 落在哪个账号"做行为断言。
"""
from __future__ import annotations

import pytest

from app.api.v1 import auth  # noqa: F401  (后续测试打桩 verify_and_get_phone 用)
from app.core import security
from app.integrations import wxpay
from app.models.phone_rebind_log import PhoneRebindLog


def _fake_userinfo(openid: str, nickname: str | None = "微信昵称", avatar: str | None = "http://x/a.png"):
    def _f(code: str) -> dict:
        return {"openid": openid, "nickname": nickname, "avatar_url": avatar, "raw": {}}
    return _f


def _sms_occupy(client, phone: str) -> int:
    """用普通短信登录占用一个手机号(register_channel=sms),返回该账号 id。"""
    assert client.post("/api/v1/auth/sms/send", json={"phone": phone}).status_code == 200
    r = client.post("/api/v1/auth/sms/login", json={"phone": phone, "code": "123456"})
    assert r.status_code == 200, r.text
    return r.json()["user"]["id"]


def _occupy_via_conflict(client, monkeypatch, openid: str, phone: str, device_id: str) -> dict:
    """微信登录(新 openid)→ 绑同一手机号 → 返回 phone_occupied 的响应体(含 conflict_ticket)。"""
    monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo(openid))
    ticket = client.post(
        "/api/v1/auth/wechat-login", json={"code": "c", "device_id": device_id}
    ).json()["bind_ticket"]
    r = client.post(
        "/api/v1/auth/wechat/bind-phone/sms",
        json={"bind_ticket": ticket, "phone": phone, "code": "123456", "device_id": device_id},
    )
    assert r.status_code == 200, r.text
    body = r.json()
    assert body["status"] == "phone_occupied"
    return body


# ===== Task 1: 模型可导入(建表由 conftest 的 create_all 完成) =====

def test_phone_rebind_log_model_importable() -> None:
    assert PhoneRebindLog.__tablename__ == "phone_rebind_log"


# ===== Task 2: conflict_ticket 令牌 =====

def test_conflict_ticket_roundtrip() -> None:
    token = security.create_conflict_ticket(
        openid="oid1", wechat_nickname="昵", wechat_avatar_url="http://a", phone="13900139000"
    )
    claims = security.decode_conflict_ticket(token)
    assert claims["openid"] == "oid1"
    assert claims["wnk"] == "昵"
    assert claims["wav"] == "http://a"
    assert claims["phone"] == "13900139000"


def test_conflict_ticket_wrong_type_rejected() -> None:
    # bind_ticket 冒充 conflict_ticket → TokenError(typ 不匹配)
    bind = security.create_bind_ticket(openid="oid", wechat_nickname=None, wechat_avatar_url=None)
    with pytest.raises(security.TokenError):
        security.decode_conflict_ticket(bind)


def test_conflict_ticket_expired_rejected(monkeypatch) -> None:
    monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
    token = security.create_conflict_ticket(
        openid="oid", wechat_nickname=None, wechat_avatar_url=None, phone="13900139000"
    )
    with pytest.raises(security.TokenError):
        security.decode_conflict_ticket(token)


# ===== Task 3: 占用响应扩展 =====

def test_phone_occupied_returns_conflict_ticket_and_flags(client, monkeypatch) -> None:
    phone = "13900139101"
    _sms_occupy(client, phone)  # 老账号 X(sms,无微信)
    body = _occupy_via_conflict(client, monkeypatch, "openid_occ_101", phone, "devO1")
    assert body["conflict_ticket"]
    assert body["rebind_available"] is True      # 首次,未换绑过
    assert body["rebind_blocked_days"] == 0
    assert body["occupied_account"]["has_wechat"] is False  # X 是 sms 账号


# ===== Task 4: 继续绑定 =====

def test_continue_attaches_wechat_and_logs_into_existing(client, monkeypatch) -> None:
    """X 无微信 → 继续绑定并入 openid + 登入 X;之后同 openid 登录直接命中 X。"""
    phone = "13900139201"
    x_id = _sms_occupy(client, phone)  # X:sms 账号,无微信
    body = _occupy_via_conflict(client, monkeypatch, "openid_cont_201", phone, "devC1")

    r = client.post(
        "/api/v1/auth/wechat/conflict/continue",
        json={"conflict_ticket": body["conflict_ticket"], "device_id": "devC1"},
    )
    assert r.status_code == 200, r.text
    assert r.json()["status"] == "logged_in"
    assert r.json()["token"]["user"]["id"] == x_id  # 登入的是老账号 X

    # openid 现已并入 X:再走 wechat-login 直接命中 X
    r = client.post("/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC1"})
    assert r.json()["status"] == "logged_in"
    assert r.json()["token"]["user"]["id"] == x_id


def test_continue_when_existing_has_wechat_logs_in_and_discards_openid(client, monkeypatch) -> None:
    """X 已绑别的微信 → 继续绑定只登入 X、丢弃本次 openid(不覆盖)。"""
    phone = "13900139202"
    # 先建一个已绑微信 O1 的账号 X(微信登录 O1 + 短信绑号)
    monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_o1_202"))
    t = client.post("/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC2"}).json()["bind_ticket"]
    x = client.post(
        "/api/v1/auth/wechat/bind-phone/sms",
        json={"bind_ticket": t, "phone": phone, "code": "123456", "device_id": "devC2"},
    ).json()
    x_id = x["token"]["user"]["id"]

    # 新 openid O2 撞同号 → 占用(has_wechat=True)→ 继续绑定
    body = _occupy_via_conflict(client, monkeypatch, "openid_o2_202", phone, "devC2b")
    assert body["occupied_account"]["has_wechat"] is True
    r = client.post(
        "/api/v1/auth/wechat/conflict/continue",
        json={"conflict_ticket": body["conflict_ticket"], "device_id": "devC2b"},
    )
    assert r.status_code == 200, r.text
    assert r.json()["token"]["user"]["id"] == x_id  # 登入 X

    # O2 被丢弃:再走 wechat-login(O2)→ 仍未命中(need_bind_phone)
    monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_o2_202"))
    assert client.post(
        "/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC2b"}
    ).json()["status"] == "need_bind_phone"


def test_continue_expired_ticket_returns_401(client, monkeypatch) -> None:
    monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
    expired = security.create_conflict_ticket(
        openid="oid", wechat_nickname=None, wechat_avatar_url=None, phone="13900139209"
    )
    r = client.post(
        "/api/v1/auth/wechat/conflict/continue",
        json={"conflict_ticket": expired, "device_id": "devC3"},
    )
    assert r.status_code == 401, r.text


# ===== Task 5: 换绑 =====

def test_rebind_creates_new_account_and_binds_openid(client, monkeypatch) -> None:
    """换绑 → 建全新微信账号 Y(≠X)+ openid 落到 Y;老账号 X 被注销(手机号归 Y)。"""
    phone = "13900139301"
    x_id = _sms_occupy(client, phone)
    body = _occupy_via_conflict(client, monkeypatch, "openid_rb_301", phone, "devR1")

    r = client.post(
        "/api/v1/auth/wechat/conflict/rebind",
        json={"conflict_ticket": body["conflict_ticket"], "device_id": "devR1"},
    )
    assert r.status_code == 200, r.text
    y = r.json()["token"]["user"]
    assert r.json()["status"] == "logged_in"
    assert y["phone"] == phone
    assert y["register_channel"] == "wechat"
    assert y["id"] != x_id  # 是全新账号,不是老账号

    # openid 落到 Y:再走 wechat-login 命中 Y
    r = client.post("/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devR1"})
    assert r.json()["status"] == "logged_in"
    assert r.json()["token"]["user"]["id"] == y["id"]


# ===== §10: continue 路径也应用展示身份回填规则 =====

def test_continue_applies_section10(client, monkeypatch) -> None:
    """§10 via M2 attach 路径: X 是默认昵称+null头像的 sms 账号;
    continue 绑定微信后,展示昵称/头像应被微信值替换,并体现在响应的 token.user 中。"""
    phone = "13900139211"
    _sms_occupy(client, phone)  # 建 X:默认昵称, null avatar
    body = _occupy_via_conflict(
        client, monkeypatch, "openid_s10", phone, "devS10"
    )  # fake_userinfo 默认 nickname="微信昵称", avatar="http://x/a.png"

    r = client.post(
        "/api/v1/auth/wechat/conflict/continue",
        json={"conflict_ticket": body["conflict_ticket"], "device_id": "devS10"},
    )
    assert r.status_code == 200, r.text
    user_out = r.json()["token"]["user"]
    assert user_out["nickname"] == "微信昵称"
    assert user_out["avatar_url"] == "http://x/a.png"


def test_rebind_blocked_within_30_days(client, monkeypatch) -> None:
    """同一手机号 30 天内二次换绑 → 409;占用响应 rebind_available=False。"""
    phone = "13900139302"
    _sms_occupy(client, phone)
    body = _occupy_via_conflict(client, monkeypatch, "openid_rb_302a", phone, "devR2")
    assert client.post(
        "/api/v1/auth/wechat/conflict/rebind",
        json={"conflict_ticket": body["conflict_ticket"], "device_id": "devR2"},
    ).status_code == 200

    # 第二次:新 openid 撞同号 → 占用响应此时 rebind_available=False
    body2 = _occupy_via_conflict(client, monkeypatch, "openid_rb_302b", phone, "devR2b")
    assert body2["rebind_available"] is False
    assert body2["rebind_blocked_days"] >= 1
    r = client.post(
        "/api/v1/auth/wechat/conflict/rebind",
        json={"conflict_ticket": body2["conflict_ticket"], "device_id": "devR2b"},
    )
    assert r.status_code == 409, r.text


def test_rebind_expired_ticket_returns_401(client, monkeypatch) -> None:
    monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
    expired = security.create_conflict_ticket(
        openid="oid", wechat_nickname=None, wechat_avatar_url=None, phone="13900139309"
    )
    r = client.post(
        "/api/v1/auth/wechat/conflict/rebind",
        json={"conflict_ticket": expired, "device_id": "devR3"},
    )
    assert r.status_code == 401, r.text
