# frozen_string_literal: true

#
# Onbrix CRM Ruby SDK
#
# A single-file Ruby SDK for the Onbrix CRM REST API.
# Provides a clean interface for managing modules, records,
# and webhook signature verification.
#
# @version 1.0.0
# @license MIT
# @see https://github.com/skbhtechnology/CRM
#
# Requirements: Ruby 3.0+, no external gems (stdlib only)
#
# Usage:
#   require_relative 'onbrix-sdk'
#
#   client = Onbrix::Client.new(api_key: 'crm_your_api_key', base_url: 'https://your-domain.com')
#   modules = client.modules.list
#   records = client.records.list('contacts', page: 1, page_size: 25)
#

require 'net/http'
require 'json'
require 'uri'
require 'openssl'

module Onbrix
  VERSION = '1.0.0'

  # --------------------------------------------------------------------------
  # Errors
  # --------------------------------------------------------------------------

  # Base error class for all Onbrix SDK errors.
  #
  # @attr_reader [String] error_code The API error code (e.g. "VALIDATION_ERROR").
  # @attr_reader [Integer] http_status The HTTP status code returned by the API.
  class Error < StandardError
    attr_reader :error_code, :http_status

    # @param message [String] Human-readable error description.
    # @param error_code [String] Machine-readable API error code.
    # @param http_status [Integer] HTTP status code.
    def initialize(message = 'An API error occurred', error_code: 'UNKNOWN_ERROR', http_status: 0)
      @error_code = error_code
      @http_status = http_status
      super(message)
    end
  end

  # Raised when the API key is missing, invalid, or expired (HTTP 401).
  class AuthenticationError < Error
    def initialize(message = 'Authentication failed', error_code: 'AUTHENTICATION_ERROR')
      super(message, error_code: error_code, http_status: 401)
    end
  end

  # Raised when the authenticated user lacks permission (HTTP 403).
  class ForbiddenError < Error
    def initialize(message = 'Access forbidden', error_code: 'FORBIDDEN')
      super(message, error_code: error_code, http_status: 403)
    end
  end

  # Raised when the requested resource does not exist (HTTP 404).
  class NotFoundError < Error
    def initialize(message = 'Resource not found', error_code: 'NOT_FOUND')
      super(message, error_code: error_code, http_status: 404)
    end
  end

  # Raised when the request body fails server-side validation (HTTP 400/422).
  class ValidationError < Error
    def initialize(message = 'Validation failed', error_code: 'VALIDATION_ERROR')
      super(message, error_code: error_code, http_status: 422)
    end
  end

  # Raised when the rate limit has been exceeded (HTTP 429).
  #
  # @attr_reader [Float] retry_after Seconds the caller should wait before retrying.
  class RateLimitError < Error
    attr_reader :retry_after

    # @param message [String] Human-readable description.
    # @param retry_after [Float] Seconds to wait before retrying.
    # @param error_code [String] Machine-readable API error code.
    def initialize(message = 'Rate limit exceeded', retry_after: 1.0, error_code: 'RATE_LIMIT_EXCEEDED')
      @retry_after = retry_after
      super(message, error_code: error_code, http_status: 429)
    end
  end

  # --------------------------------------------------------------------------
  # HTTP Transport
  # --------------------------------------------------------------------------

  # Low-level HTTP client using Net::HTTP.
  #
  # Handles request signing, JSON encoding/decoding, error mapping,
  # and automatic retry with exponential backoff on 429 responses.
  #
  # @api private
  class HttpClient
    # Rate-limit metadata from the most recent response.
    #
    # @return [Hash{Symbol => Integer, nil}]
    attr_reader :rate_limit_info

    # @param api_key [String] The API key (should start with "crm_").
    # @param base_url [String] The base URL of the Onbrix instance.
    # @param max_retries [Integer] Maximum retries on HTTP 429.
    # @param initial_retry_delay [Float] Initial backoff delay in seconds.
    # @param open_timeout [Integer] Connection open timeout in seconds.
    # @param read_timeout [Integer] Read timeout in seconds.
    def initialize(api_key:, base_url:, max_retries: 3, initial_retry_delay: 1.0,
                   open_timeout: 10, read_timeout: 30)
      @api_key = api_key
      @base_url = base_url.chomp('/')
      @max_retries = max_retries
      @initial_retry_delay = initial_retry_delay
      @open_timeout = open_timeout
      @read_timeout = read_timeout
      @rate_limit_info = { limit: nil, remaining: nil, reset: nil }
    end

    # Perform an HTTP request against the Onbrix API.
    #
    # @param method [Symbol] HTTP verb (:get, :post, :put, :delete).
    # @param path [String] API path relative to /api/v1 (e.g. "/contacts").
    # @param body [Hash, nil] Request body (will be JSON-encoded).
    # @param query [Hash] Query-string parameters.
    #
    # @return [Hash] Parsed JSON response body.
    #
    # @raise [AuthenticationError]
    # @raise [ForbiddenError]
    # @raise [NotFoundError]
    # @raise [ValidationError]
    # @raise [RateLimitError] Only raised when all retries are exhausted.
    # @raise [Error] For any other API or transport error.
    def request(method, path, body: nil, query: {})
      uri = build_uri(path, query)
      attempt = 0
      delay = @initial_retry_delay

      loop do
        req = build_request(method, uri, body)
        response = execute_request(uri, req)

        parse_rate_limit_headers(response)

        if response.code.to_i == 429
          retry_after = extract_retry_after(response, delay)

          if attempt < @max_retries
            sleep(retry_after)
            attempt += 1
            delay *= 2
            next
          end

          raise RateLimitError.new(
            "Rate limit exceeded after #{attempt + 1} attempts",
            retry_after: retry_after
          )
        end

        decoded = parse_response_body(response)
        handle_error_status(response.code.to_i, decoded) if response.code.to_i >= 400

        return decoded
      end
    end

    private

    # Build the full URI including query parameters.
    #
    # @param path [String] API path.
    # @param query [Hash] Query parameters.
    # @return [URI::HTTPS, URI::HTTP]
    def build_uri(path, query)
      url = "#{@base_url}/api/v1#{path}"
      uri = URI.parse(url)

      unless query.empty?
        params = URI.encode_www_form(query)
        uri.query = uri.query ? "#{uri.query}&#{params}" : params
      end

      uri
    end

    # Build a Net::HTTP request object.
    #
    # @param method [Symbol] HTTP verb.
    # @param uri [URI] Full request URI.
    # @param body [Hash, nil] Request body.
    # @return [Net::HTTPRequest]
    def build_request(method, uri, body)
      request_class = {
        get: Net::HTTP::Get,
        post: Net::HTTP::Post,
        put: Net::HTTP::Put,
        delete: Net::HTTP::Delete
      }.fetch(method) { raise ArgumentError, "Unsupported HTTP method: #{method}" }

      req = request_class.new(uri)
      req['X-API-Key'] = @api_key
      req['Accept'] = 'application/json'
      req['User-Agent'] = "Onbrix-Ruby-SDK/#{VERSION}"

      if body && %i[post put].include?(method)
        json_body = JSON.generate(body)
        req['Content-Type'] = 'application/json'
        req.body = json_body
      end

      req
    end

    # Execute the HTTP request with configured timeouts.
    #
    # @param uri [URI] Request URI.
    # @param req [Net::HTTPRequest] The request object.
    # @return [Net::HTTPResponse]
    # @raise [Error] On connection failure.
    def execute_request(uri, req)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = (uri.scheme == 'https')
      http.open_timeout = @open_timeout
      http.read_timeout = @read_timeout

      http.request(req)
    rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ETIMEDOUT,
           Net::OpenTimeout, Net::ReadTimeout, SocketError => e
      raise Error.new("Network error: #{e.message}", error_code: 'NETWORK_ERROR')
    end

    # Parse rate-limit headers from the response.
    #
    # @param response [Net::HTTPResponse]
    def parse_rate_limit_headers(response)
      @rate_limit_info[:limit] = response['X-RateLimit-Limit']&.to_i
      @rate_limit_info[:remaining] = response['X-RateLimit-Remaining']&.to_i
      @rate_limit_info[:reset] = response['X-RateLimit-Reset']&.to_i
    end

    # Extract Retry-After value from response, falling back to computed delay.
    #
    # @param response [Net::HTTPResponse]
    # @param fallback [Float]
    # @return [Float]
    def extract_retry_after(response, fallback)
      header = response['Retry-After']
      header ? header.to_f : fallback
    end

    # Parse the response body as JSON.
    #
    # @param response [Net::HTTPResponse]
    # @return [Hash]
    # @raise [Error] On JSON parse failure for error responses.
    def parse_response_body(response)
      body = response.body.to_s.strip
      return {} if body.empty?

      JSON.parse(body, symbolize_names: false)
    rescue JSON::ParserError => e
      if response.code.to_i >= 200 && response.code.to_i < 300
        return {}
      end

      raise Error.new(
        "Failed to parse API response (HTTP #{response.code}): #{e.message}",
        error_code: 'PARSE_ERROR',
        http_status: response.code.to_i
      )
    end

    # Map an HTTP error status to the appropriate SDK error class.
    #
    # @param status [Integer] HTTP status code.
    # @param body [Hash] Parsed response body.
    # @raise [AuthenticationError]
    # @raise [ForbiddenError]
    # @raise [NotFoundError]
    # @raise [ValidationError]
    # @raise [Error]
    def handle_error_status(status, body)
      message = body['error'] || "HTTP #{status} error"
      code = body['code'] || 'UNKNOWN_ERROR'

      case status
      when 401
        raise AuthenticationError.new(message, error_code: code)
      when 403
        raise ForbiddenError.new(message, error_code: code)
      when 404
        raise NotFoundError.new(message, error_code: code)
      when 400, 422
        raise ValidationError.new(message, error_code: code)
      else
        raise Error.new(message, error_code: code, http_status: status)
      end
    end
  end

  # --------------------------------------------------------------------------
  # Resource Classes
  # --------------------------------------------------------------------------

  # Provides access to module-level API endpoints.
  #
  # Obtained via `client.modules`.
  class ModulesResource
    # @api private
    # @param http [HttpClient]
    def initialize(http)
      @http = http
    end

    # List all modules available to the authenticated user.
    #
    # @return [Array<Hash>] Array of module hashes.
    # @raise [Error]
    def list
      response = @http.request(:get, '/modules')
      response['data'] || []
    end
  end

  # Provides access to record-level CRUD endpoints.
  #
  # Obtained via `client.records`.
  class RecordsResource
    # @api private
    # @param http [HttpClient]
    def initialize(http)
      @http = http
    end

    # List records within a module.
    #
    # @param module_slug [String] The module slug (e.g. "contacts", "deals").
    # @param page [Integer] Page number (1-based).
    # @param page_size [Integer] Number of records per page.
    # @param sort_by [String, nil] Field name to sort by.
    # @param sort_dir [String, nil] Sort direction ("asc" or "desc").
    # @param search [String, nil] Free-text search query.
    # @param filters [Hash] Field-value filter pairs.
    #
    # @return [Hash] Response hash with "data" (Array) and "meta" keys.
    # @raise [Error]
    def list(module_slug, page: 1, page_size: 25, sort_by: nil, sort_dir: nil, search: nil, filters: {})
      query = {}
      query['page'] = page.to_s
      query['page_size'] = page_size.to_s
      query['sort_by'] = sort_by if sort_by
      query['sort_dir'] = sort_dir if sort_dir
      query['search'] = search if search

      filters.each do |field, value|
        query["filter[#{field}]"] = value.to_s
      end

      @http.request(:get, "/#{uri_encode(module_slug)}", query: query)
    end

    # Retrieve a single record by ID.
    #
    # @param module_slug [String] The module slug.
    # @param record_id [String] The record UUID.
    #
    # @return [Hash] Response hash with "data" key containing the record.
    # @raise [NotFoundError] If the record does not exist.
    # @raise [Error]
    def get(module_slug, record_id)
      @http.request(:get, "/#{uri_encode(module_slug)}/#{uri_encode(record_id)}")
    end

    # Create a new record in a module.
    #
    # @param module_slug [String] The module slug.
    # @param data [Hash] Field values for the new record.
    #
    # @return [Hash] Response hash with "data" key containing the created record.
    # @raise [ValidationError] If the data fails validation.
    # @raise [Error]
    def create(module_slug, data)
      @http.request(:post, "/#{uri_encode(module_slug)}", body: { 'data' => data })
    end

    # Update an existing record.
    #
    # @param module_slug [String] The module slug.
    # @param record_id [String] The record UUID.
    # @param data [Hash] Field values to update.
    #
    # @return [Hash] Response hash with "data" key containing the updated record.
    # @raise [NotFoundError] If the record does not exist.
    # @raise [ValidationError] If the data fails validation.
    # @raise [Error]
    def update(module_slug, record_id, data)
      @http.request(:put, "/#{uri_encode(module_slug)}/#{uri_encode(record_id)}", body: { 'data' => data })
    end

    # Delete a record.
    #
    # @param module_slug [String] The module slug.
    # @param record_id [String] The record UUID.
    #
    # @return [Hash] Response hash with "data" key containing {id, deleted: true}.
    # @raise [NotFoundError] If the record does not exist.
    # @raise [Error]
    def delete(module_slug, record_id)
      @http.request(:delete, "/#{uri_encode(module_slug)}/#{uri_encode(record_id)}")
    end

    # Auto-paginate through all records in a module.
    #
    # Returns an Enumerator that lazily fetches pages as you iterate.
    # Each yielded value is a single record hash.
    #
    # @example Iterate all contacts
    #   client.records.list_all('contacts', page_size: 100).each do |record|
    #     puts record['id']
    #   end
    #
    # @example Convert to array (fetches all pages)
    #   all_contacts = client.records.list_all('contacts').to_a
    #
    # @param module_slug [String] The module slug.
    # @param options [Hash] Keyword arguments forwarded to {#list} (except page).
    # @option options [Integer] :page_size (100) Records per page.
    # @option options [String] :sort_by Field to sort by.
    # @option options [String] :sort_dir Sort direction.
    # @option options [String] :search Free-text search.
    # @option options [Hash] :filters Field-value filter pairs.
    #
    # @return [Enumerator<Hash>] Lazy enumerator yielding individual record hashes.
    # @raise [Error]
    def list_all(module_slug, **options)
      options[:page_size] ||= 100

      Enumerator.new do |yielder|
        page = 1

        loop do
          response = list(module_slug, page: page, **options)

          records = response['data'] || []
          records.each { |record| yielder.yield(record) }

          meta = response['meta'] || {}
          total_pages = meta['total_pages'] || 1

          break if page >= total_pages

          page += 1
        end
      end.lazy
    end

    private

    # URI-encode a path segment.
    #
    # @param value [String]
    # @return [String]
    def uri_encode(value)
      URI.encode_uri_component(value.to_s)
    end
  end

  # --------------------------------------------------------------------------
  # Client
  # --------------------------------------------------------------------------

  # Main entry point for the Onbrix CRM Ruby SDK.
  #
  # @example Basic usage
  #   client = Onbrix::Client.new(api_key: 'crm_your_api_key', base_url: 'https://your-domain.com')
  #
  #   # List modules
  #   modules = client.modules.list
  #
  #   # CRUD operations
  #   contacts = client.records.list('contacts', page_size: 10)
  #   contact  = client.records.get('contacts', 'uuid-here')
  #   created  = client.records.create('contacts', { 'first_name' => 'Alice' })
  #   updated  = client.records.update('contacts', created['data']['id'], { 'last_name' => 'Smith' })
  #   deleted  = client.records.delete('contacts', created['data']['id'])
  #
  #   # Auto-paginate
  #   client.records.list_all('contacts').each { |r| puts r['id'] }
  #
  #   # Verify webhook
  #   valid = Onbrix::Client.verify_webhook_signature(
  #     payload: raw_body, signature: header_value, secret: 'whsec_...'
  #   )
  class Client
    # Create a new Onbrix API client.
    #
    # @param api_key [String] Your API key (should start with "crm_").
    # @param base_url [String] The base URL of your Onbrix instance.
    # @param max_retries [Integer] Maximum retries on HTTP 429 (default: 3).
    # @param retry_delay [Float] Initial backoff delay in seconds (default: 1.0).
    # @param open_timeout [Integer] Connection timeout in seconds (default: 10).
    # @param read_timeout [Integer] Read timeout in seconds (default: 30).
    #
    # @raise [ArgumentError] If api_key or base_url is empty.
    def initialize(api_key:, base_url:, max_retries: 3, retry_delay: 1.0,
                   open_timeout: 10, read_timeout: 30)
      raise ArgumentError, 'API key must not be empty' if api_key.nil? || api_key.strip.empty?
      raise ArgumentError, 'Base URL must not be empty' if base_url.nil? || base_url.strip.empty?

      @http = HttpClient.new(
        api_key: api_key,
        base_url: base_url,
        max_retries: max_retries,
        initial_retry_delay: retry_delay,
        open_timeout: open_timeout,
        read_timeout: read_timeout
      )

      @modules_resource = nil
      @records_resource = nil
    end

    # Access the Modules resource for listing available modules.
    #
    # @return [ModulesResource]
    def modules
      @modules_resource ||= ModulesResource.new(@http)
    end

    # Access the Records resource for CRUD operations on module records.
    #
    # @return [RecordsResource]
    def records
      @records_resource ||= RecordsResource.new(@http)
    end

    # Return rate-limit metadata from the most recent API response.
    #
    # @return [Hash{Symbol => Integer, nil}] Keys: :limit, :remaining, :reset.
    def rate_limit_info
      @http.rate_limit_info
    end

    # Verify that an incoming webhook payload was signed by Onbrix.
    #
    # Compares the provided signature header value against a locally computed
    # HMAC-SHA256 digest of the raw request body. Uses constant-time comparison
    # via OpenSSL.secure_compare to prevent timing attacks.
    #
    # @example Sinatra webhook handler
    #   post '/webhooks/onbrix' do
    #     payload   = request.body.read
    #     signature = request.env['HTTP_X_WEBHOOK_SIGNATURE'] || ''
    #     secret    = ENV['ONBRIX_WEBHOOK_SECRET']
    #
    #     unless Onbrix::Client.verify_webhook_signature(payload: payload, signature: signature, secret: secret)
    #       halt 401, 'Invalid signature'
    #     end
    #
    #     event = JSON.parse(payload)
    #     # process event...
    #     status 200
    #   end
    #
    # @param payload [String] The raw JSON request body.
    # @param signature [String] The value of the X-Webhook-Signature header (e.g. "sha256=abcdef...").
    # @param secret [String] The webhook endpoint secret.
    #
    # @return [Boolean] True if the signature is valid, false otherwise.
    def self.verify_webhook_signature(payload:, signature:, secret:)
      prefix = 'sha256='

      return false unless signature.start_with?(prefix)

      provided_hmac = signature[prefix.length..]
      computed_hmac = OpenSSL::HMAC.hexdigest('SHA256', secret, payload)

      secure_compare(computed_hmac, provided_hmac)
    end

    # Constant-time string comparison to prevent timing attacks.
    #
    # @param a [String]
    # @param b [String]
    # @return [Boolean]
    # @api private
    def self.secure_compare(a, b)
      return false unless a.bytesize == b.bytesize

      # Use OpenSSL's fixed-length comparison if available (Ruby 2.7+),
      # otherwise fall back to a manual constant-time check.
      if defined?(OpenSSL.fixed_length_secure_compare)
        OpenSSL.fixed_length_secure_compare(a, b)
      else
        result = 0
        a.bytes.zip(b.bytes) { |x, y| result |= x ^ y }
        result.zero?
      end
    rescue StandardError
      false
    end

    private_class_method :secure_compare
  end
end
