"""alipay 模块单测（非网络）。

重点覆盖 sandbox / prod 切换逻辑（issue #028）。真实 HTTP 调用不在此测，
留给后续 L2 E2E（alpha 真跑 sandbox precreate）。
"""

from __future__ import annotations

import pytest


def test_is_sandbox_default_false(monkeypatch):
    monkeypatch.delenv("XIANGQIN_ALIPAY_SANDBOX", raising=False)
    from xiangqin import alipay

    assert alipay._is_sandbox() is False


@pytest.mark.parametrize("val", ["1", "true", "True", "yes", "YES"])
def test_is_sandbox_truthy_values(monkeypatch, val):
    monkeypatch.setenv("XIANGQIN_ALIPAY_SANDBOX", val)
    from xiangqin import alipay

    assert alipay._is_sandbox() is True


@pytest.mark.parametrize("val", ["0", "false", "no", "", "anything-else"])
def test_is_sandbox_falsey_values(monkeypatch, val):
    monkeypatch.setenv("XIANGQIN_ALIPAY_SANDBOX", val)
    from xiangqin import alipay

    assert alipay._is_sandbox() is False


def test_get_gateway_prod(monkeypatch):
    monkeypatch.delenv("XIANGQIN_ALIPAY_SANDBOX", raising=False)
    from xiangqin import alipay

    assert alipay._get_gateway() == alipay.ALIPAY_GATEWAY_PROD
    assert "openapi.alipay.com" in alipay._get_gateway()


def test_get_gateway_sandbox(monkeypatch):
    monkeypatch.setenv("XIANGQIN_ALIPAY_SANDBOX", "1")
    from xiangqin import alipay

    assert alipay._get_gateway() == alipay.ALIPAY_GATEWAY_SANDBOX
    assert "alipaydev.com" in alipay._get_gateway()


def test_get_conf_reads_prod_credential(monkeypatch):
    """非 sandbox 时调 creds.get('alipay')。"""
    monkeypatch.delenv("XIANGQIN_ALIPAY_SANDBOX", raising=False)
    from xiangqin import alipay, credentials

    called_keys = []

    def fake_get(key):
        called_keys.append(key)
        return {
            "app_id": "prod_app",
            "app_private_key": "-----BEGIN PRIVATE KEY-----\nprodkey\n-----END PRIVATE KEY-----",
            "alipay_public_key": "-----BEGIN PUBLIC KEY-----\nprodpub\n-----END PUBLIC KEY-----",
        }

    monkeypatch.setattr(credentials, "get", fake_get)
    conf = alipay._get_conf()
    assert called_keys == ["alipay"]
    assert conf["app_id"] == "prod_app"


def test_get_conf_reads_sandbox_credential(monkeypatch):
    """XIANGQIN_ALIPAY_SANDBOX=1 时调 creds.get('alipay_sandbox')。"""
    monkeypatch.setenv("XIANGQIN_ALIPAY_SANDBOX", "1")
    from xiangqin import alipay, credentials

    called_keys = []

    def fake_get(key):
        called_keys.append(key)
        return {
            "app_id": "sandbox_app",
            "app_private_key": "-----BEGIN PRIVATE KEY-----\nsandkey\n-----END PRIVATE KEY-----",
            "alipay_public_key": "-----BEGIN PUBLIC KEY-----\nsandpub\n-----END PUBLIC KEY-----",
        }

    monkeypatch.setattr(credentials, "get", fake_get)
    conf = alipay._get_conf()
    assert called_keys == ["alipay_sandbox"]
    assert conf["app_id"] == "sandbox_app"
