<?php

// php tests/run.php  — starts sdks/testing/mock_server.py (Python 3 on PATH) and runs the SDK against it.

declare(strict_types=1);

require __DIR__ . '/../src/HBankException.php';
require __DIR__ . '/../src/HBankClient.php';
require __DIR__ . '/../src/Callback.php';

use HBank\Callback;
use HBank\HBankClient;
use HBank\HBankException;

$port = random_int(8400, 8499);
$base = "http://127.0.0.1:{$port}";
$python = PHP_OS_FAMILY === 'Windows' ? 'python' : 'python3';
$proc = proc_open([$python, __DIR__ . '/../../testing/mock_server.py', '--port', (string) $port], [1 => ['pipe', 'w']], $pipes);
fgets($pipes[1]);

$failures = 0;
function test(string $name, callable $body): void
{
    global $failures;
    try {
        $body();
        echo "ok   {$name}\n";
    } catch (Throwable $e) {
        $failures++;
        echo "FAIL {$name}: {$e}\n";
    }
}
function eq(mixed $expected, mixed $actual): void
{
    if ($expected != $actual) {
        throw new RuntimeException('expected ' . var_export($expected, true) . ', got ' . var_export($actual, true));
    }
}
function fails(callable $body): HBankException
{
    try {
        $body();
    } catch (HBankException $e) {
        return $e;
    }
    throw new RuntimeException('expected an HBankException');
}
$pay = fn (string $tid) => file_get_contents("{$base}/_mock/pay/{$tid}", false, stream_context_create(['http' => ['method' => 'POST']]));

$bank = new HBankClient('test_key', $base);

test('payment, QR code, refund', function () use ($bank, $base, $pay) {
    $tid = $bank->createPayment(24.9, 'EUR', 'Order 1042', 'https://shop.example/cb');
    eq("{$base}/api/payment?tid={$tid}", $bank->checkoutUrl($tid));
    eq(true, str_ends_with($bank->createPaymentCode($tid)['qr_svg'], '/qr.svg'));
    eq('pending', $bank->getPayment($tid)['status']);
    eq(24.9, $bank->getPayment($tid)['amount']);
    $pay($tid);
    $r = $bank->refund($tid, '10', 'Returned one item');
    eq(14.9, $r['transaction']['refundable']);
    eq('amount_too_high', fails(fn () => $bank->refund($tid, 100))->errorCode);
});

test('errors', function () use ($bank, $base) {
    $e = fails(fn () => $bank->createPayment(0, 'EUR'));
    eq(['invalid_amount', 400], [$e->errorCode, $e->status]);
    eq('transaction_not_found', fails(fn () => $bank->getPayment('tx_NoSuchPayment0000000000000'))->errorCode);
    eq(true, fails(fn () => (new HBankClient('nope', $base))->listSubscriptions())->isAuthentication());
    eq(true, fails(fn () => (new HBankClient('k', 'http://127.0.0.1:1', 3))->rate('EUR', 'USD'))->isConnection());
});

test('subscriptions', function () use ($bank, $pay) {
    $s = $bank->createSubscription('9.99', 'EUR', 'month', 1, 'Pro plan');
    eq('offered', $s['status']);
    $c = $bank->checkoutSubscription($s['id']);
    $pay($c['transaction_id']);
    eq('active', $bank->getSubscription($s['id'])['status']);
    eq('merchant', $bank->cancelSubscription($s['id'])['canceled_by']);
    eq('already_canceled', fails(fn () => $bank->cancelSubscription($s['id']))->errorCode);
    eq(2, $bank->createSubscriptionCheckout(5, 'EUR', 'week', 2)['subscription']['interval_count']);
});

test('several subscriptions in one checkout', function () use ($bank, $pay) {
    $storage = $bank->createSubscription(5, 'EUR', 'month', 1, 'Storage');
    $c = $bank->createSubscriptionsCheckout([$storage['id'], ['amount' => '2.50', 'currency' => 'EUR', 'interval' => 'week', 'description' => 'Support']],
        callbackUrl: 'https://shop.example/cb');
    eq(['Storage', 'Support'], array_column($c['subscriptions'], 'description'));
    eq($storage['id'], $c['subscriptions'][0]['id']);
    $pay($c['transaction_id']);
    $payment = $bank->getPayment($c['transaction_id']);
    eq(7.5, $payment['amount']);
    eq(array_column($c['subscriptions'], 'id'), $payment['subscription_ids']);
    foreach ($c['subscriptions'] as $x) eq('active', $bank->getSubscription($x['id'])['status']);
    eq('not_open', fails(fn () => $bank->createSubscriptionsCheckout([$storage['id']]))->errorCode);
    eq('mixed_currencies', fails(fn () => $bank->createSubscriptionsCheckout([
        ['amount' => 1, 'currency' => 'EUR', 'interval' => 'month'], ['amount' => 1, 'currency' => 'USD', 'interval' => 'month']]))->errorCode);
});

test('currencies', function () use ($bank) {
    eq(108.37, $bank->convert(100, 'EUR', 'USD'));
    eq(1.0837, $bank->rate('EUR', 'USD')['to_rate']);
});

test('callbacks', function () {
    $cb = Callback::parse('{"id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "amount": 24.90, "currency": "EUR", "status": "completed", "description": "Order 1042"}');
    eq(['tx_8fK2mQ7xRb4Tn9WcYz3LpH6v', '24.90'], [$cb->id, $cb->amount]);
    eq(['resume' => false, 'error' => 'Out of stock'], Callback::refuse('Out of stock'));
    eq('invalid_callback', fails(fn () => Callback::parse('{}'))->errorCode);
});

test('callback signature', function () {
    $body = '{"id":7310,"amount":24.9,"currency":"EUR","status":"awaiting_approval","description":"Order 1042"}';
    $header = 't=1700000000,v1=fcfc30b9667c3a8e8aea68178c36716153e075f79c61521bf3586088d9877281';
    eq(true, Callback::verifySignature('hbcb_test', $header, $body, 300, 1700000100));
    eq(false, Callback::verifySignature('hbcb_other', $header, $body, 300, 1700000100));
    eq(false, Callback::verifySignature('hbcb_test', $header, '{}', 300, 1700000100));
    eq(false, Callback::verifySignature('hbcb_test', $header, $body, 300, 1700000400));
    eq(false, Callback::verifySignature('hbcb_test', 'garbage', $body, 300, 1700000100));
});

proc_terminate($proc);
echo $failures === 0 ? "All passed.\n" : "{$failures} failed.\n";
exit($failures === 0 ? 0 : 1);
