# ruby -Ilib test/hbank_test.rb — starts sdks/testing/mock_server.py (Python 3 on PATH) and runs the SDK against it.
require "minitest/autorun"
require "net/http"
require "stringio"
require "hbank"

PORT = rand(8300..8399)
BASE = "http://127.0.0.1:#{PORT}"
SERVER = IO.popen([Gem.win_platform? ? "python" : "python3", File.expand_path("../../testing/mock_server.py", __dir__),
                   "--port", PORT.to_s])
SERVER.gets
Minitest.after_run { Process.kill("TERM", SERVER.pid) }

class HBankTest < Minitest::Test
  def bank = @bank ||= HBank::Client.new(api_key: "test_key", base_url: BASE)
  def pay(tid) = Net::HTTP.post(URI("#{BASE}/_mock/pay/#{tid}"), "")

  def test_payment_flow
    tid = bank.create_payment(amount: "24.90", currency: "EUR", description: "Order 1042", callback_url: "https://shop.example/cb")
    assert_equal "#{BASE}/api/payment?tid=#{tid}", bank.checkout_url(tid)
    assert bank.create_payment_code(tid)[:qr_svg].end_with?("/qr.svg")
    assert_equal BigDecimal("24.90"), bank.get_payment(tid)[:amount]
    pay(tid)
    r = bank.refund(tid, amount: 10, reason: "Returned one item")
    assert_equal BigDecimal("14.90"), r[:transaction][:refundable]
    e = assert_raises(HBank::Error) { bank.refund(tid, amount: 100) }
    assert_equal ["amount_too_high", 400], [e.code, e.status]
  end

  def test_errors
    assert_equal "invalid_amount", assert_raises(HBank::Error) { bank.create_payment(amount: 0, currency: "EUR") }.code
    assert_equal 404, assert_raises(HBank::Error) { bank.get_payment("tx_NoSuchPayment0000000000000") }.status
    assert_raises(HBank::AuthenticationError) { HBank::Client.new(api_key: "nope", base_url: BASE).list_subscriptions }
    assert_raises(HBank::ConnectionError) { HBank::Client.new(api_key: "k", base_url: "http://127.0.0.1:1").rate("EUR", "USD") }
  end

  def test_subscriptions
    s = bank.create_subscription(amount: "9.99", currency: "EUR", interval: "month", description: "Pro plan")
    assert_equal "offered", s[:status]
    c = bank.checkout_subscription(s[:id])
    pay(c[:transaction_id])
    assert_equal "active", bank.get_subscription(s[:id])[:status]
    assert_equal "merchant", bank.cancel_subscription(s[:id])[:canceled_by]
    assert_equal "already_canceled", assert_raises(HBank::Error) { bank.cancel_subscription(s[:id]) }.code
  end

  def test_several_subscriptions_in_one_checkout
    storage = bank.create_subscription(amount: 5, currency: "EUR", interval: "month", description: "Storage")
    c = bank.create_subscriptions_checkout([storage[:id], { amount: "2.50", currency: "EUR", interval: "week", description: "Support" }],
                                           callback_url: "https://shop.example/cb")
    assert_equal %w[Storage Support], c[:subscriptions].map { |x| x[:description] }
    assert_equal storage[:id], c[:subscriptions][0][:id]
    pay(c[:transaction_id])
    payment = bank.get_payment(c[:transaction_id])
    assert_equal BigDecimal("7.50"), payment[:amount]
    assert_equal c[:subscriptions].map { |x| x[:id] }, payment[:subscription_ids]
    c[:subscriptions].each { |x| assert_equal "active", bank.get_subscription(x[:id])[:status] }
    assert_equal "not_open", assert_raises(HBank::Error) { bank.create_subscriptions_checkout([storage[:id]]) }.code
    mixed = [{ amount: 1, currency: "EUR", interval: "month" }, { amount: 1, currency: "USD", interval: "month" }]
    assert_equal "mixed_currencies", assert_raises(HBank::Error) { bank.create_subscriptions_checkout(mixed) }.code
  end

  def test_currency
    assert_equal BigDecimal("108.37"), bank.convert(100, "EUR", "USD")
    assert_equal BigDecimal("1.0837"), bank.rate("EUR", "USD")[:to_rate]
  end

  def test_callback
    cb = HBank::Callback.parse('{"id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "amount": 24.90, "currency": "EUR"}')
    assert_equal ["tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", BigDecimal("24.90")], [cb.id, cb.amount]
    app = HBank::Callback.rack { |c| c.amount == BigDecimal("24.9") || "Wrong amount" }
    status, headers, body = app.call("rack.input" => StringIO.new('{"id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "amount": 5, "currency": "EUR"}'))
    assert_equal [200, "application/json", '{"resume":false,"error":"Wrong amount"}'], [status, headers["content-type"], body.first]
    assert_raises(HBank::Error) { HBank::Callback.parse("{}") }
  end

  def test_callback_signature
    body = '{"id":7310,"amount":24.9,"currency":"EUR","status":"awaiting_approval","description":"Order 1042"}'
    header = "t=1700000000,v1=fcfc30b9667c3a8e8aea68178c36716153e075f79c61521bf3586088d9877281"
    assert HBank::Callback.verify_signature("hbcb_test", header, body, now: 1_700_000_100)
    refute HBank::Callback.verify_signature("hbcb_other", header, body, now: 1_700_000_100)
    refute HBank::Callback.verify_signature("hbcb_test", header, "{}", now: 1_700_000_100)
    refute HBank::Callback.verify_signature("hbcb_test", header, body, now: 1_700_000_400)
    refute HBank::Callback.verify_signature("hbcb_test", "garbage", body, now: 1_700_000_100)
    app = HBank::Callback.rack(secret: "hbcb_test") { true }
    _, _, out = app.call("rack.input" => StringIO.new(body))
    assert_equal '{"resume":false,"error":"Invalid callback"}', out.first
  end
end
