<?php

declare(strict_types=1);

namespace HBank;

/**
 * Client for the HBank merchant API (v1). Needs the curl extension.
 *
 *     $bank = new \HBank\HBankClient(getenv('HBANK_API_KEY'));
 *     $tid = $bank->createPayment('24.90', 'EUR', 'Order 1042', 'https://shop.example/hbank/callback');
 *     header('Location: ' . $bank->checkoutUrl($tid));
 *
 * Answers are associative arrays with the API's field names (see the API docs). Pass amounts as strings ('24.90')
 * to avoid float rounding; they're sent as strings, which the API accepts. Failures throw HBankException.
 */
final class HBankClient
{
    public const DEFAULT_BASE_URL = 'https://bank.thehsi.cloud';

    private string $baseUrl;

    public function __construct(
        private readonly string $apiKey,
        ?string $baseUrl = null,
        private readonly int $timeoutSeconds = 30,
    ) {
        if ($apiKey === '') {
            throw new \InvalidArgumentException('API key is required');
        }
        $this->baseUrl = rtrim($baseUrl ?? self::DEFAULT_BASE_URL, '/');
    }

    // ── Payments ─────────────────────────────────────────────

    /** Creates a pending payment request and returns its transaction id. It stays payable for one hour. */
    public function createPayment(string|int|float $amount, string $currency, ?string $description = null, ?string $callbackUrl = null): string
    {
        $body = self::compact(['amount' => self::amount($amount), 'currency' => $currency,
            'description' => $description, 'callback_url' => $callbackUrl]);
        return (string) $this->post('payment/request', $body)['transaction_id'];
    }

    /**
     * A QR code / link for a pending payment. Calling it again returns the same code.
     * @return array{code: string, url: string, qr_svg: string}
     */
    public function createPaymentCode(string $transactionId): array
    {
        $d = $this->post('payment/code', ['transaction_id' => $transactionId]);
        return ['code' => $d['code'], 'url' => $d['url'], 'qr_svg' => $d['qr_svg']];
    }

    /**
     * The current state of one of your payments. Check `status === 'completed'` before handing out goods.
     * @return array{id: string, type: string, amount: float, currency: string, status: string, description: string,
     *     reference: ?string, payment_code: ?string, refunded: float, refundable: float, refund_of: ?string, subscription_id: ?string,
     *     subscription_ids: list<string>}  (subscription_ids: every subscription the payment belongs to)
     */
    public function getPayment(string $transactionId): array
    {
        return $this->post('payment/details', ['transaction_id' => $transactionId])['transaction'];
    }

    /**
     * Refunds (part of) a completed payment: $amount in its currency, or everything that's left when null.
     * Not safe to blindly retry after a timeout: check `refunded` with getPayment() first.
     * @return array{refund: array, transaction: array}
     */
    public function refund(string $transactionId, string|int|float|null $amount = null, ?string $reason = null): array
    {
        $d = $this->post('payment/refund', self::compact(['transaction_id' => $transactionId,
            'amount' => $amount === null ? null : self::amount($amount), 'reason' => $reason]));
        return ['refund' => $d['refund'], 'transaction' => $d['transaction']];
    }

    /** The hosted checkout (card number + PIN) for a payment. The payment needs a callback URL. */
    public function checkoutUrl(string $transactionId): string
    {
        return $this->baseUrl . '/api/payment?tid=' . rawurlencode($transactionId);
    }

    // ── Subscriptions ────────────────────────────────────────

    /** Offers a subscription ($interval: day, week, month or year). Send the customer its `url`. */
    public function createSubscription(string|int|float $amount, string $currency, string $interval, int $intervalCount = 1, ?string $description = null): array
    {
        return $this->post('subscriptions', self::offer($amount, $currency, $interval, $intervalCount, $description))['subscription'];
    }

    /**
     * Offers a subscription and creates its first payment, for the pay button / hosted checkout.
     * @return array{transaction_id: string, subscription: array}
     */
    public function createSubscriptionCheckout(string|int|float $amount, string $currency, string $interval, int $intervalCount = 1,
                                               ?string $description = null, ?string $callbackUrl = null): array
    {
        $body = self::offer($amount, $currency, $interval, $intervalCount, $description) + self::compact(['callback_url' => $callbackUrl]);
        $d = $this->post('subscriptions/checkout', $body);
        return ['transaction_id' => (string) $d['transaction_id'], 'subscription' => $d['subscription']];
    }

    /**
     * One first payment for several subscriptions (up to 20, one currency). Each item is the id of a subscription you
     * offered ('sub_…') or a new offer's fields: ['amount' => …, 'currency' => …, 'interval' => …, 'interval_count' => …,
     * 'description' => …]. Paying it starts them all; after that each renews on its own. When one is refused, nothing
     * is offered.
     * @param list<string|array> $subscriptions
     * @return array{transaction_id: string, subscriptions: list<array>}
     */
    public function createSubscriptionsCheckout(array $subscriptions, ?string $description = null, ?string $callbackUrl = null): array
    {
        $items = array_map(fn ($item) => is_string($item) ? $item : self::offer($item['amount'], $item['currency'], $item['interval'],
            (int) ($item['interval_count'] ?? 1), $item['description'] ?? null), array_values($subscriptions));
        $body = ['subscriptions' => $items] + self::compact(['description' => $description, 'callback_url' => $callbackUrl]);
        $d = $this->post('subscriptions/checkout', $body);
        return ['transaction_id' => (string) $d['transaction_id'], 'subscriptions' => $d['subscriptions']];
    }

    /**
     * A new first payment for a subscription already offered (`not_open` once someone subscribed).
     * @return array{transaction_id: string, subscription: array}
     */
    public function checkoutSubscription(string $subscriptionId, ?string $callbackUrl = null): array
    {
        $d = $this->post("subscriptions/" . rawurlencode($subscriptionId) . "/checkout", self::compact(['callback_url' => $callbackUrl]));
        return ['transaction_id' => (string) $d['transaction_id'], 'subscription' => $d['subscription']];
    }

    /** Your subscriptions, newest first (up to 100). */
    public function listSubscriptions(): array
    {
        return $this->get('subscriptions')['subscriptions'];
    }

    public function getSubscription(string $subscriptionId): array
    {
        return $this->get("subscriptions/" . rawurlencode($subscriptionId))['subscription'];
    }

    /** No more charges. It stays in its `active_period` until `current_period_end`. */
    public function cancelSubscription(string $subscriptionId): array
    {
        return $this->post("subscriptions/" . rawurlencode($subscriptionId) . "/cancel", [])['subscription'];
    }

    // ── Currencies ───────────────────────────────────────────

    public function convert(string|int|float $amount, string $from, string $to): float
    {
        $q = http_build_query(['amount' => self::amount($amount), 'currency_from' => $from, 'currency_to' => $to]);
        return (float) $this->get('currency/convert?' . $q)['amount'];
    }

    /** @return array{to_rate: float, from_rate: float} to_rate converts $from into $to; from_rate the other way. */
    public function rate(string $from, string $to): array
    {
        $d = $this->get('currency/rate?' . http_build_query(['currency_from' => $from, 'currency_to' => $to]));
        return ['to_rate' => (float) $d['to_rate'], 'from_rate' => (float) $d['from_rate']];
    }

    // ── Transport ────────────────────────────────────────────

    private function get(string $path): array
    {
        return $this->send('GET', $path, null);
    }

    private function post(string $path, array $body): array
    {
        return $this->send('POST', $path, json_encode((object) $body, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES));
    }

    private function send(string $method, string $path, ?string $body): array
    {
        $headers = ['Authorization: Bearer ' . $this->apiKey, 'Accept: application/json'];
        if ($body !== null) {
            $headers[] = 'Content-Type: application/json';
        }
        $ch = curl_init($this->baseUrl . '/api/v1/' . $path);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $this->timeoutSeconds,
            CURLOPT_CONNECTTIMEOUT => min(10, $this->timeoutSeconds),
            CURLOPT_USERAGENT => 'hbank-php/1.0',
        ]);
        if ($body !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        }
        $text = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($text === false) {
            $timedOut = curl_errno($ch) === CURLE_OPERATION_TIMEDOUT;
            $error = curl_error($ch);
            curl_close($ch);
            throw new HBankException($timedOut ? 'timeout' : 'connection_failed', 0, $error);
        }
        curl_close($ch);

        $trimmed = trim((string) $text);
        if ($status === 401) {
            throw new HBankException('missing_api_key', $status, $trimmed ?: null);
        }
        if ($status === 403) {
            throw new HBankException('invalid_api_key', $status, $trimmed ?: null);
        }
        $json = json_decode((string) $text, true, 64, JSON_BIGINT_AS_STRING);
        if (!is_array($json)) {
            throw new HBankException('invalid_response', $status, substr($trimmed, 0, 200) ?: null);
        }
        if ($status < 200 || $status >= 300 || ($json['success'] ?? null) === false) {
            throw new HBankException(is_string($json['error'] ?? null) ? $json['error'] : "http_{$status}", $status,
                is_string($json['message'] ?? null) ? $json['message'] : null, $json);
        }
        return $json;
    }

    private static function amount(string|int|float $value): string
    {
        if (is_float($value)) {
            if (!is_finite($value)) {
                throw new \InvalidArgumentException('amount must be finite');
            }
            // Shortest text that round-trips (serialize_precision -1), e.g. 24.9 -> "24.9". The API doesn't take
            // exponents, so tiny/huge values fall back to fixed notation.
            $text = json_encode($value);
            return str_contains($text, 'e') || str_contains($text, 'E')
                ? rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.')
                : $text;
        }
        return trim((string) $value);
    }

    private static function offer(string|int|float $amount, string $currency, string $interval, int $intervalCount, ?string $description): array
    {
        return self::compact(['amount' => self::amount($amount), 'currency' => $currency, 'interval' => $interval,
            'interval_count' => $intervalCount, 'description' => $description]);
    }

    private static function compact(array $a): array
    {
        return array_filter($a, static fn ($v) => $v !== null);
    }
}
