# frozen_string_literal: true

require "bigdecimal"
require "json"
require "net/http"
require "openssl"
require "uri"

# Client for the HBank merchant API (v1). Standard library only.
#
#   bank = HBank::Client.new(api_key: ENV.fetch("HBANK_API_KEY"))
#   tid = bank.create_payment(amount: "24.90", currency: "EUR", description: "Order 1042",
#                             callback_url: "https://shop.example/hbank/callback")
#   redirect_to bank.checkout_url(tid), allow_other_host: true
#
# Answers are Hashes with symbol keys and the API's field names; amounts are BigDecimal, so no digits are lost.
module HBank
  VERSION = "1.2.0"
  DEFAULT_BASE_URL = "https://bank.thehsi.cloud"

  # The API answered with an error. +code+ is machine-readable ("invalid_amount", "transaction_not_found", ...),
  # +status+ the HTTP status (nil when HBank couldn't be reached), +detail+ the readable message some errors carry.
  class Error < StandardError
    attr_reader :code, :status, :detail, :body

    def initialize(code, status = nil, detail = nil, body = nil)
      super(detail ? "#{code}: #{detail}" : code.to_s)
      @code = code
      @status = status
      @detail = detail
      @body = body
    end
  end

  # 401 missing_api_key or 403 invalid_api_key.
  class AuthenticationError < Error; end

  # HBank couldn't be reached or didn't answer in time ("connection_failed" / "timeout"). The request may or may not
  # have reached HBank: before retrying a refund, check :refunded with get_payment.
  class ConnectionError < Error; end

  class Client
    attr_reader :base_url

    def initialize(api_key:, base_url: DEFAULT_BASE_URL, timeout: 30)
      raise ArgumentError, "api_key is required" if api_key.nil? || api_key.empty?

      @api_key = api_key
      @base_url = base_url.sub(%r{/+\z}, "")
      @timeout = timeout
    end

    # ── Payments ─────────────────────────────────────────────

    # Creates a pending payment request and returns its transaction id. It stays payable for one hour.
    def create_payment(amount:, currency:, description: nil, callback_url: nil)
      post("payment/request", compact(amount: amount_text(amount), currency: currency,
                                      description: description, callback_url: callback_url))[:transaction_id]
    end

    # A QR code / link for a pending payment: { code:, url:, qr_svg: }. Calling it again returns the same code.
    def create_payment_code(transaction_id)
      post("payment/code", transaction_id: transaction_id).slice(:code, :url, :qr_svg)
    end

    # The current state of one of your payments. Check payment[:status] == "completed" before handing out goods.
    def get_payment(transaction_id)
      post("payment/details", transaction_id: transaction_id)[:transaction]
    end

    # Refunds (part of) a completed payment: amount in its currency, or everything that's left when nil.
    # Returns { refund:, transaction: }. Not safe to blindly retry after a timeout: check :refunded first.
    def refund(transaction_id, amount: nil, reason: nil)
      post("payment/refund", compact(transaction_id: transaction_id, amount: amount && amount_text(amount),
                                     reason: reason)).slice(:refund, :transaction)
    end

    # The hosted checkout (card number + PIN) for a payment. The payment needs a callback URL.
    def checkout_url(transaction_id)
      "#{@base_url}/api/payment?tid=#{URI.encode_www_form_component(transaction_id.to_s)}"
    end

    # ── Subscriptions ────────────────────────────────────────

    # Offers a subscription (interval: "day", "week", "month" or "year"). Send the customer its :url.
    def create_subscription(amount:, currency:, interval:, interval_count: 1, description: nil)
      post("subscriptions", offer(amount, currency, interval, interval_count, description))[:subscription]
    end

    # Offers a subscription and creates its first payment: { transaction_id:, subscription: }.
    def create_subscription_checkout(amount:, currency:, interval:, interval_count: 1, description: nil, callback_url: nil)
      body = offer(amount, currency, interval, interval_count, description).merge(compact(callback_url: callback_url))
      post("subscriptions/checkout", body).slice(:transaction_id, :subscription)
    end

    # One first payment for several subscriptions (up to 20, one currency): { transaction_id:, subscriptions: }. Each item
    # is the id of a subscription you offered ("sub_…") or a new offer's fields as a hash (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. Payment details list them in :subscription_ids.
    def create_subscriptions_checkout(subscriptions, description: nil, callback_url: nil)
      items = subscriptions.map do |item|
        next item.to_s unless item.is_a?(Hash)

        offer(item.fetch(:amount), item.fetch(:currency), item.fetch(:interval), item.fetch(:interval_count, 1), item[:description])
      end
      post("subscriptions/checkout", { subscriptions: items }.merge(compact(description: description, callback_url: callback_url)))
        .slice(:transaction_id, :subscriptions)
    end

    # A new first payment for a subscription already offered ("not_open" once someone subscribed).
    def checkout_subscription(subscription_id, callback_url: nil)
      post("subscriptions/#{URI.encode_www_form_component(subscription_id.to_s)}/checkout", compact(callback_url: callback_url))
        .slice(:transaction_id, :subscription)
    end

    # Your subscriptions, newest first (up to 100).
    def list_subscriptions
      get("subscriptions")[:subscriptions]
    end

    def get_subscription(subscription_id)
      get("subscriptions/#{URI.encode_www_form_component(subscription_id.to_s)}")[:subscription]
    end

    # No more charges. It stays in its :active_period until :current_period_end.
    def cancel_subscription(subscription_id)
      post("subscriptions/#{URI.encode_www_form_component(subscription_id.to_s)}/cancel", {})[:subscription]
    end

    # ── Currencies ───────────────────────────────────────────

    def convert(amount, from, to)
      get("currency/convert", amount: amount_text(amount), currency_from: from, currency_to: to)[:amount]
    end

    # { to_rate:, from_rate: }: to_rate converts from into to; from_rate the other way.
    def rate(from, to)
      get("currency/rate", currency_from: from, currency_to: to).slice(:to_rate, :from_rate)
    end

    private

    def get(path, query = nil)
      path += "?#{URI.encode_www_form(query)}" if query
      send_request(Net::HTTP::Get.new(uri(path)))
    end

    def post(path, body)
      request = Net::HTTP::Post.new(uri(path))
      request["Content-Type"] = "application/json"
      request.body = JSON.generate(body)
      send_request(request)
    end

    def uri(path)
      URI("#{@base_url}/api/v1/#{path}")
    end

    def send_request(request)
      request["Authorization"] = "Bearer #{@api_key}"
      request["Accept"] = "application/json"
      request["User-Agent"] = "hbank-ruby/#{VERSION}"
      target = request.uri
      begin
        response = Net::HTTP.start(target.host, target.port, use_ssl: target.scheme == "https",
                                                             open_timeout: [@timeout, 10].min, read_timeout: @timeout,
                                                             write_timeout: @timeout) { |http| http.request(request) }
      rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout => e
        raise ConnectionError.new("timeout", nil, e.message)
      rescue SystemCallError, SocketError, IOError, OpenSSL::SSL::SSLError => e
        raise ConnectionError.new("connection_failed", nil, e.message)
      end

      status = response.code.to_i
      text = response.body.to_s
      raise AuthenticationError.new("missing_api_key", status, text.strip) if status == 401
      raise AuthenticationError.new("invalid_api_key", status, text.strip) if status == 403

      json = begin
        JSON.parse(text, symbolize_names: true, decimal_class: BigDecimal)
      rescue JSON::ParserError
        nil
      end
      raise Error.new("invalid_response", status, text[0, 200]) unless json.is_a?(Hash)

      if status < 200 || status >= 300 || json[:success] == false
        code = json[:error].is_a?(String) ? json[:error] : "http_#{status}"
        raise Error.new(code, status, json[:message], json)
      end
      json
    end

    # Amounts go over the wire as strings, which the API accepts, so no digits are lost.
    def amount_text(value)
      case value
      when BigDecimal then value.to_s("F")
      when Integer, Float, String then value.to_s.strip
      else raise ArgumentError, "amount must be a number or a numeric string"
      end
    end

    def offer(amount, currency, interval, interval_count, description)
      compact(amount: amount_text(amount), currency: currency, interval: interval, interval_count: interval_count,
              description: description)
    end

    def compact(hash)
      hash.reject { |_, v| v.nil? }
    end
  end

  # HBank's callback: right before charging a customer, HBank POSTs the payment to its callback URL and charges only
  # if you answer 200 with {"resume": true} as application/json within 10 seconds.
  #
  # It's signed: check the HBank-Signature header with your business's signing secret (business settings → Callback
  # URLs) before you approve, with verify_signature (or rack(secret: ...)). Also check that id and amount match an order
  # you created, and confirm with get_payment before handing out goods.
  #
  #   # Rails (skip_forgery_protection in this controller)
  #   def hbank_callback
  #     unless HBank::Callback.verify_signature(ENV["HBANK_CALLBACK_SECRET"], request.headers["HBank-Signature"], request.raw_post)
  #       return render json: HBank::Callback.refuse("Invalid callback")
  #     end
  #     cb = HBank::Callback.parse(request.raw_post)
  #     order = Order.find_by(hbank_transaction_id: cb.id)
  #     render json: order&.total == cb.amount ? HBank::Callback.approve : HBank::Callback.refuse("Out of stock")
  #   end
  Callback = Struct.new(:id, :amount, :currency, :status, :description, keyword_init: true) do
    # Reads a callback body. Raises HBank::Error("invalid_callback") if it isn't one.
    def self.parse(body)
      d = JSON.parse(body, decimal_class: BigDecimal)
      unless d.is_a?(Hash) && d["id"].is_a?(String) && !d["id"].empty? && d["amount"] && d["currency"].is_a?(String)
        raise Error.new("invalid_callback", nil, "missing or invalid id, amount or currency")
      end

      new(id: d["id"], amount: BigDecimal(d["amount"].to_s), currency: d["currency"],
          status: d["status"].to_s, description: d["description"].to_s)
    rescue JSON::ParserError, ArgumentError => e
      raise Error.new("invalid_callback", nil, e.message)
    end

    # Whether header (the request's HBank-Signature: "t=<unix time>,v1=<hex>") signs body (the raw request body, exactly
    # as received) with secret, and was made within tolerance seconds of now.
    def self.verify_signature(secret, header, body, tolerance: 300, now: Time.now.to_i)
      return false if secret.nil? || secret.empty? || header.nil? || header.empty?

      parts = {}
      header.split(",").each do |part|
        key, value = part.split("=", 2)
        parts[key] ||= value if value
      end
      t = parts["t"].to_s
      return false unless t.match?(/\A\d{1,18}\z/) && (now - t.to_i).abs <= tolerance

      expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{body}")
      given = parts["v1"].to_s
      expected.bytesize == given.bytesize && OpenSSL.fixed_length_secure_compare(expected, given)
    end

    # Lets HBank charge the customer.
    def self.approve
      { resume: true }
    end

    # Refuses the payment; the customer sees error.
    def self.refuse(error = nil)
      error ? { resume: false, error: error } : { resume: false }
    end

    # A Rack app for the callback URL (Sinatra, Hanami, Roda, or `mount` in Rails routes):
    #   map("/hbank/callback") { run HBank::Callback.rack { |cb| Order.matches?(cb.id, cb.amount) } }
    # The block returns true (charge), false, or a String shown to the customer (refuse). With secret:, a callback
    # without a valid HBank-Signature is refused ("Invalid callback") before the block runs.
    def self.rack(secret: nil, &decide)
      lambda do |env|
        answer = begin
          body = env["rack.input"].read
          if secret && !verify_signature(secret, env["HTTP_HBANK_SIGNATURE"], body)
            raise Error.new("invalid_callback", nil, "bad or missing HBank-Signature")
          end

          decision = decide.call(parse(body))
          decision == true ? approve : refuse(decision.is_a?(String) ? decision : nil)
        rescue Error
          refuse("Invalid callback")
        rescue StandardError
          refuse("The shop couldn't confirm this order")
        end
        [200, { "content-type" => "application/json" }, [JSON.generate(answer)]]
      end
    end
  end
end
