"""Tests for the USDT-TRC20 and Stripe-crypto payment rails."""

import sys
from pathlib import Path

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

BACKEND_DIR = Path(__file__).parent.parent
sys.path.insert(0, str(BACKEND_DIR))
sys.path.insert(0, str(BACKEND_DIR / "plugins"))

import payments_plugin  # noqa: E402
from fastapi_integration import _build_payments_config  # noqa: E402

USDT_CONTRACT = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"


def make_client(monkeypatch: pytest.MonkeyPatch, config: dict) -> tuple[TestClient, dict]:
    """Build a FastAPI app hosting only the payments plugin, with an in-memory store."""
    store = {"orders": {}, "balances": {}, "credit_txs": []}
    monkeypatch.setattr(payments_plugin, "_load_store", lambda: store)
    monkeypatch.setattr(payments_plugin, "_save_store", lambda s: None)
    app = FastAPI()
    plugin = payments_plugin.PaymentsPlugin().bind({"payments_config": config})
    plugin.register(app)
    return TestClient(app), store


def checkout(client: TestClient, method: str, user_id: str = "u-test") -> dict:
    response = client.post(
        "/payments/checkout",
        json={"product_id": "karma", "user_id": user_id, "currency": "usd", "method": method},
    )
    assert response.status_code == 200, response.text
    return response.json()


def test_build_payments_config_includes_tron_keys(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("MERCHANT_TRON_ADDRESS", "TTestMerchantAddress")
    monkeypatch.setenv("TRONGRID_API_KEY", "tg-key")
    monkeypatch.delenv("USDT_TRC20_CONTRACT", raising=False)
    config = _build_payments_config()
    assert config["merchant_tron_address"] == "TTestMerchantAddress"
    assert config["trongrid_api_key"] == "tg-key"
    assert config["trongrid_base_url"] == "https://api.trongrid.io"
    assert config["usdt_trc20_contract"] == USDT_CONTRACT
