# frozen_string_literal: true

module Dispatch
  module Adapter
    class OverloadedError < RateLimitError; end

    module ClaudeErrors
      module_function

      PROVIDER = "Anthropic (Claude)"

      def handle_response!(response)
        return if response.is_a?(Net::HTTPSuccess)

        code = response.code.to_i
        msg  = parse_message(response.body)
        retry_after = response["Retry-After"]&.to_i

        case code
        when 401, 403 then raise AuthenticationError.new(msg, status_code: code, provider: PROVIDER)
        when 429      then raise RateLimitError.new(msg, status_code: code, provider: PROVIDER, retry_after:)
        when 529      then raise OverloadedError.new(msg, status_code: code, provider: PROVIDER, retry_after:)
        when 400, 422 then raise RequestError.new(msg, status_code: code, provider: PROVIDER)
        when 500..599 then raise ServerError.new(msg, status_code: code, provider: PROVIDER)
        else raise Error.new(msg, status_code: code, provider: PROVIDER)
        end
      end

      def parse_message(body)
        JSON.parse(body.to_s).dig("error", "message") || body.to_s
      rescue JSON::ParserError
        body.to_s
      end
    end
  end
end
