module Billing
  module Stripe
    # Metadati e subscription id su Invoice (API Basil+: parent.subscription_details).
    module InvoiceMetadata
      module_function

      def merged(invoice)
        base = metadata_hash(invoice)
        base.merge(subscription_metadata(invoice))
      end

      def subscription_metadata(invoice)
        details = subscription_details(invoice)
        return {} if details.blank?

        metadata_hash(details)
      end

      def subscription_id(invoice)
        details = subscription_details(invoice)
        return nil if details.blank?

        InvoicePaymentRefs.safe_get(details, :subscription)
      end

      def subscription_details(invoice)
        parent = InvoicePaymentRefs.safe_get(invoice, :parent)
        return nil if parent.blank?

        InvoicePaymentRefs.safe_get(parent, :subscription_details)
      end

      def metadata_hash(obj)
        meta = InvoicePaymentRefs.safe_get(obj, :metadata)
        meta.to_h.stringify_keys
      rescue NoMethodError
        {}
      end
    end
  end
end
