# MIT License
#
# Copyright (c) 2026 Email Validation LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# email-validation.org connector for Workato (Connector SDK, https://docs.workato.com/developing-connectors/sdk.html).
#
# One definition file, pasted into Tools > Connector SDK (https://email-validation.org/docs/guides/workato/#setup).
# Every request goes through the
# `api_request` method: the key goes out as `Authorization: Bearer` only to our two API hosts over HTTPS, redirects
# are never followed, and every non-2xx answer becomes a job error that starts with our error code in brackets
# (`[insufficient_credits] ...`), carries the request id and never the key or the address. The connector never
# retries by itself: no action sets `retry_on_response`, so Workato sends each request once.
{
  title: 'email-validation.org',

  connection: {
    fields: [
      {
        name: 'api_key',
        label: 'API key',
        control_type: 'password',
        optional: false,
        hint: 'Create a key under <a href="https://email-validation.org/app/api-keys/" target="_blank">' \
              'Dashboard &gt; API keys</a> with <b>Validate addresses</b> and <b>Read balance and usage</b> ' \
              '(both on by default; the connection test reads your credit balance). The bulk actions also ' \
              'need <b>Bulk lists</b>.'
      },
      {
        name: 'region',
        label: 'API host',
        control_type: 'select',
        options: [
          ['api.email-validation.org', 'us'],
          ['api-eu.email-validation.org (EU data residency)', 'eu']
        ],
        default: 'us',
        optional: true,
        hint: 'Pick the EU host if you use <a href="https://email-validation.org/docs/eu-data-residency/" ' \
              'target="_blank">EU data residency</a>. Same key, credits and prices.'
      }
    ],

    authorization: {
      type: 'api_key',

      # Runs before every request. The key is added only to requests for one of our two API hosts over HTTPS;
      # `api_request` sends nothing else (it takes only `/v1/` paths on the connection's base URI).
      apply: lambda do |connection|
        url = current_url.to_s
        ours = ['https://api.email-validation.org/', 'https://api-eu.email-validation.org/'].any? do |origin|
          url.start_with?(origin)
        end
        if ours
          headers('Authorization' => "Bearer #{connection['api_key'].to_s.strip}",
                  'User-Agent' => 'email-validation-workato/1.0.0')
        end
      end
    },

    base_uri: lambda do |connection|
      connection['region'] == 'eu' ? 'https://api-eu.email-validation.org' : 'https://api.email-validation.org'
    end
  },

  # The connection test reads the credit balance: free, and it needs the key's "Read balance and usage" permission.
  test: lambda do |connection|
    call('api_request', connection, 'get', '/v1/credits', {})
  end,

  methods: {
    # The one request path (the connection's key is checked first). `options`: 'params' (query), 'json' (a JSON body), 'body' (raw text) with
    # 'content_type', 'accept' ('json' default, or 'csv' for the results file).
    api_request: lambda do |connection, verb, path, options|
      key = connection['api_key'].to_s.strip
      error('[invalid_request] Enter your API key from Dashboard > API keys, without spaces.') unless key.match?(/\A\S+\z/)
      error('[invalid_request] This connector only calls the email-validation.org API.') unless path.to_s.start_with?('/v1/')
      request =
        case verb
        when 'get' then get(path)
        when 'post' then post(path)
        when 'delete' then delete(path)
        else error("[invalid_request] Unsupported method #{verb}.")
        end
      request = request.params(options['params']) if options['params'].present?
      if options['json'].present?
        request = request.payload(options['json']).request_format_json
      elsif options['body'].present?
        request = request.request_body(options['body']).headers('Content-Type' => options['content_type'] || 'text/csv')
      end
      csv = options['accept'] == 'csv'
      request.
        headers('Accept' => csv ? 'text/csv' : 'application/json').
        response_format_raw.
        ignore_redirection.
        after_response do |code, body, response_headers|
          if code.to_i >= 300
            call('raise_api_error', code, body, response_headers, key)
          elsif csv
            # a results file never holds the key: one that does is not ours (a broken or hostile proxy)
            if call('shares_key', body.to_s, key)
              error("[unexpected_response] The API answered with a file that is not a results file. (HTTP #{code.to_i})")
            end
            body.to_s
          else
            call('parse_json_body', code, body, response_headers, key)
          end
        end.
        after_error_response(/.*/) do |code, body, response_headers, _message|
          call('raise_api_error', code, body, response_headers, key)
        end
    end,

    # What our API answers is passed on only in our own shape (our error codes, request ids and reasons) and never
    # with 12 characters of the key in a row (a broken or hostile proxy in front of our API that quotes the
    # Authorization header back).
    shares_key: lambda do |text, key|
      if key.length < 12
        key.present? && text.include?(key)
      else
        (0..(key.length - 12)).any? { |i| text.include?(key[i, 12]) }
      end
    end,

    code_of: lambda do |value, key|
      value.is_a?(String) && value.match?(/\A[a-z][a-z0-9_]{0,63}\z/) && !call('shares_key', value, key) ? value : nil
    end,

    request_id_of: lambda do |value, key|
      value.is_a?(String) && value.match?(/\Areq_[A-Za-z0-9]{1,60}\z/) && !call('shares_key', value, key) ? value : nil
    end,

    # A copy of a value without any string that holds a run of the key: null in an object, left out of an array; an
    # object's name that holds one is left out with its value.
    without_key: lambda do |value, key|
      if value.is_a?(String)
        call('shares_key', value, key) ? nil : value
      elsif value.is_a?(Array)
        value.reject { |v| v.is_a?(String) && call('shares_key', v, key) }.map { |v| call('without_key', v, key) }
      elsif value.is_a?(Hash)
        copy = {}
        value.each { |name, v| copy[name] = call('without_key', v, key) unless call('shares_key', name.to_s, key) }
        copy
      else
        value
      end
    end,

    # The JSON object of a 2xx answer, without anything that quotes the key: the reason kept only in our shape, the
    # request id and the error code only as ours. A body that is not one is an error that never repeats the body (a
    # parser's message quotes its input, which could hold an address).
    parse_json_body: lambda do |code, body, response_headers, key|
      parsed = call('parse_json_or_nil', body)
      unless parsed.is_a?(Hash)
        request_id = call('request_id_of', call('response_header', response_headers, 'X-Request-Id'), key)
        details = ["HTTP #{code.to_i}", request_id.present? ? "request #{request_id}" : nil].compact.join(', ')
        error("[unexpected_response] The API answered with something other than JSON. (#{details})")
      end
      copy = call('without_key', parsed, key)
      if parsed.key?('reason')
        reason = copy['reason']
        copy['reason'] = reason.is_a?(String) && reason.match?(/\A[a-z_]{1,64}\z/) ? reason : ''
      end
      copy['request_id'] = call('request_id_of', parsed['request_id'], key) if parsed.key?('request_id')
      copy['error_code'] = call('code_of', parsed['error_code'], key) if parsed.key?('error_code')
      copy
    end,

    parse_json_or_nil: lambda do |body|
      text = body.to_s.strip
      if text.start_with?('{')
        begin
          workato.parse_json(text)
        rescue StandardError
          nil
        end
      end
    end,

    # A header from Workato's response headers, whichever way their names are spelled.
    response_header: lambda do |response_headers, name|
      response_headers ||= {}
      response_headers[name] || response_headers[name.downcase] || response_headers[name.downcase.tr('-', '_')] ||
        response_headers[name.downcase.tr('-', '_').to_sym]
    end,

    # Turns a non-2xx answer into a job error: "[code] message advice (HTTP status, request req_...)".
    # Our error envelope is { "error": { "code", "message", "request_id" } }; `message` is for people.
    # Only our code, a message that does not quote the key, our request id and a Retry-After of seconds or an HTTP
    # date are kept from an error answer.
    raise_api_error: lambda do |code, body, response_headers, key|
      status = code.to_i
      if status >= 300 && status < 400
        error("[unexpected_response] The API answered with a redirect (HTTP #{status}), which this connector never follows.")
      end
      envelope = {}
      parsed = call('parse_json_or_nil', body)
      envelope = parsed['error'] if parsed.is_a?(Hash) && parsed['error'].is_a?(Hash)
      api_code = call('code_of', envelope['code'], key) || "http_#{status}"
      api_message = envelope['message'].is_a?(String) && envelope['message'].present? && !call('shares_key', envelope['message'], key) ? envelope['message'] : "The API answered HTTP #{status}."
      # the body's request id when it is one of ours, else the header's
      request_id = call('request_id_of', envelope['request_id'], key) ||
                   call('request_id_of', call('response_header', response_headers, 'X-Request-Id'), key)
      retry_after = call('response_header', response_headers, 'Retry-After').to_s.strip
      wait =
        if retry_after.match?(/\A\d+\z/)
          "Try again in #{retry_after} s."
        elsif retry_after.match?(/\A[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT\z/)
          "Try again after #{retry_after}."
        else
          'Try again in a minute.'
        end
      advice =
        case api_code
        when 'unauthorized'
          'Check the API key in this connection (Dashboard > API keys).'
        when 'insufficient_credits'
          'Nothing was charged. Buy credits in the dashboard, then rerun the job.'
        when 'forbidden'
          'The key lacks a permission this action needs (Dashboard > API keys).'
        when 'rate_limited', 'abuse_throttled', 'service_unavailable', 'upstream_capacity'
          "Nothing was charged. #{wait}"
        when 'key_daily_cap'
          "This key reached its daily limit, set under Dashboard > API keys. #{wait}"
        else
          status >= 500 ? 'Try again later.' : ''
        end
      details = ["HTTP #{status}", request_id.present? ? "request #{request_id}" : nil].compact.join(', ')
      error(["[#{api_code}]", api_message, advice.presence, "(#{details})"].compact.join(' '))
    end,

    # Bulk job ids are checked before they go into a URL path.
    job_path: lambda do |job_id, suffix|
      id = job_id.to_s.strip
      error('[invalid_request] Enter a bulk job id (job_ followed by 22 letters and digits).') unless id.match?(/\Ajob_[0-9A-Za-z]{22}\z/)
      "/v1/bulk/#{id}#{suffix}"
    end,

    # Optional true/false inputs: nil when left empty, so the API's default applies.
    flag: lambda do |value|
      text = value.to_s.strip.downcase
      if %w[true yes 1].include?(text)
        true
      elsif %w[false no 0].include?(text)
        false
      end
    end,

    bulk_job_finished: lambda do |job|
      %w[completed failed cancelled expired].include?(job['status']) ||
        (job['status'] == 'ready' && job['error_code'].present?)
    end,

    sample_validation_result: lambda do
      {
        'email' => 'accepted@sandbox.email-validation.org',
        'status' => 'valid',
        'reason' => 'accepted',
        'action' => 'send',
        'account' => 'accepted',
        'domain' => 'sandbox.email-validation.org',
        'did_you_mean' => nil,
        'free_email' => false,
        'role_account' => false,
        'disposable' => false,
        'catch_all_domain' => false,
        'mx_found' => true,
        'mx_record' => 'mx.sandbox.email-validation.org',
        'smtp_provider' => 'other',
        'domain_age_days' => 3650,
        'processed_at' => '2026-10-20T09:30:00.000Z',
        'credits_used' => 0,
        'request_id' => 'req_7Hq2LmX9cV4bN8tR1zK6wD'
      }
    end,

    sample_credits: lambda do
      {
        'balance' => 24_350,
        'debt' => 0,
        'pending' => 0,
        'lots' => [
          { 'remaining' => 850, 'expires_at' => '2027-03-14T12:00:00.000Z' },
          { 'remaining' => 23_500, 'expires_at' => '2028-09-30T08:15:00.000Z' }
        ]
      }
    end,

    sample_bulk_job: lambda do
      {
        'id' => 'job_3Fv8QpL2xM7nC1rT9kW4yB',
        'status' => 'completed',
        'filename' => nil,
        'total_rows' => 12_480,
        'unique_emails' => 12_061,
        'duplicates' => 378,
        'syntax_invalid' => 41,
        'local_answered' => 0,
        'processed' => 12_061,
        'credits_reserved' => 12_061,
        'credits_charged' => 11_874,
        'counts' => { 'valid' => 10_406, 'invalid' => 977, 'catch_all' => 401, 'unknown' => 187, 'disposable' => 90 },
        'error_code' => nil,
        'webhook_endpoint_id' => 'whk_9Lp4XcV2nB7mQ1tR6zK3wF',
        'created_at' => '2026-10-20T09:30:00.000Z',
        'started_at' => '2026-10-20T09:30:41.000Z',
        'finished_at' => '2026-10-20T09:52:07.000Z',
        'expires_at' => '2026-11-19T09:30:00.000Z'
      }
    end
  },

  object_definitions: {
    validation_result: {
      fields: lambda do |_connection, _config_fields, _object_definitions|
        [
          { name: 'email', label: 'Email', hint: 'The address as you sent it, without surrounding spaces. For reason normalized, the corrected address.' },
          { name: 'status', label: 'Status', hint: 'One of valid, invalid, catch_all, unknown, disposable.' },
          { name: 'reason', label: 'Reason', hint: 'Why the address got its status, for example accepted, no_mailbox or catch_all.' },
          { name: 'action', label: 'Action', hint: 'What to do with the address: send, send_with_caution, remove or retry_later.' },
          { name: 'account', label: 'Account', hint: 'The part before the @ of the address.' },
          { name: 'domain', label: 'Domain', hint: 'The part after the @ (international domains in ASCII form).' },
          { name: 'did_you_mean', label: 'Did you mean', hint: 'A suggested correction when the address looks like a typo of a common domain.' },
          { name: 'free_email', label: 'Free email provider', type: 'boolean', control_type: 'checkbox' },
          { name: 'role_account', label: 'Role account', type: 'boolean', control_type: 'checkbox', hint: 'True when the address belongs to a team or function (such as info@ or sales@) rather than a person.' },
          { name: 'disposable', label: 'Disposable', type: 'boolean', control_type: 'checkbox', hint: 'True when the address comes from a throwaway inbox service.' },
          { name: 'catch_all_domain', label: 'Catch-all domain', type: 'boolean', control_type: 'checkbox', hint: 'True when the domain accepts mail for any address.' },
          { name: 'mx_found', label: 'MX found', type: 'boolean', control_type: 'checkbox', hint: 'True when the domain publishes mail (MX) records.' },
          { name: 'mx_record', label: 'MX record', hint: 'The preferred mail server host for the domain.' },
          { name: 'smtp_provider', label: 'SMTP provider', hint: 'Who runs the mail server, for example google or microsoft.' },
          { name: 'domain_age_days', label: 'Domain age (days)', type: 'integer', control_type: 'integer' },
          { name: 'processed_at', label: 'Processed at', type: 'date_time', control_type: 'date_time', hint: 'When this result was produced (UTC).' },
          { name: 'credits_used', label: 'Credits used', type: 'integer', control_type: 'integer', hint: '1 when this check cost a credit; unknown results, malformed addresses and sandbox addresses are free.' },
          { name: 'request_id', label: 'Request ID', hint: 'Quote it to support.' }
        ]
      end
    },

    credits: {
      fields: lambda do |_connection, _config_fields, _object_definitions|
        [
          { name: 'balance', label: 'Balance', type: 'integer', control_type: 'integer', hint: 'Credits you can spend now.' },
          { name: 'debt', label: 'Debt', type: 'integer', control_type: 'integer' },
          { name: 'pending', label: 'Pending', type: 'integer', control_type: 'integer' },
          {
            name: 'lots', label: 'Credit lots', type: 'array', of: 'object', hint: 'Soonest-expiring first.',
            properties: [
              { name: 'remaining', label: 'Remaining', type: 'integer', control_type: 'integer' },
              { name: 'expires_at', label: 'Expires at', type: 'date_time', control_type: 'date_time' }
            ]
          }
        ]
      end
    },

    bulk_job: {
      fields: lambda do |_connection, _config_fields, _object_definitions|
        [
          { name: 'id', label: 'Job ID' },
          { name: 'status', label: 'Status', hint: 'analyzing, ready, queued, running, cancelling, finalizing, completed, failed, cancelled or expired.' },
          { name: 'filename', label: 'File name' },
          { name: 'total_rows', label: 'Total rows', type: 'integer', control_type: 'integer' },
          { name: 'unique_emails', label: 'Unique emails', type: 'integer', control_type: 'integer' },
          { name: 'duplicates', label: 'Duplicates', type: 'integer', control_type: 'integer' },
          { name: 'syntax_invalid', label: 'Syntax invalid', type: 'integer', control_type: 'integer' },
          { name: 'local_answered', label: 'Answered without a check', type: 'integer', control_type: 'integer' },
          { name: 'processed', label: 'Processed', type: 'integer', control_type: 'integer' },
          { name: 'credits_reserved', label: 'Credits reserved', type: 'integer', control_type: 'integer' },
          { name: 'credits_charged', label: 'Credits charged', type: 'integer', control_type: 'integer' },
          {
            name: 'counts', label: 'Counts', type: 'object', hint: 'Addresses per status so far.',
            properties: [
              { name: 'valid', label: 'Valid', type: 'integer', control_type: 'integer' },
              { name: 'invalid', label: 'Invalid', type: 'integer', control_type: 'integer' },
              { name: 'catch_all', label: 'Catch-all', type: 'integer', control_type: 'integer' },
              { name: 'unknown', label: 'Unknown', type: 'integer', control_type: 'integer' },
              { name: 'disposable', label: 'Disposable', type: 'integer', control_type: 'integer' }
            ]
          },
          { name: 'error_code', label: 'Error code', hint: 'Why a job failed or waits in ready, for example insufficient_credits.' },
          { name: 'webhook_endpoint_id', label: 'Webhook endpoint ID' },
          { name: 'created_at', label: 'Created at', type: 'date_time', control_type: 'date_time' },
          { name: 'started_at', label: 'Started at', type: 'date_time', control_type: 'date_time' },
          { name: 'finished_at', label: 'Finished at', type: 'date_time', control_type: 'date_time' },
          { name: 'expires_at', label: 'Expires at', type: 'date_time', control_type: 'date_time' }
        ]
      end
    },

    job_id_input: {
      fields: lambda do |_connection, _config_fields, _object_definitions|
        [
          { name: 'job_id', label: 'Job ID', optional: false, hint: 'The id of a bulk job (job_ followed by 22 letters and digits), from Create bulk job.' }
        ]
      end
    }
  },

  pick_lists: {
    results_filters: lambda do |_connection|
      [
        ['All rows', 'all'],
        %w[Valid valid],
        %w[Invalid invalid],
        ['Catch-all', 'catch_all'],
        %w[Unknown unknown],
        %w[Disposable disposable]
      ]
    end,

    results_columns: lambda do |_connection|
      [
        ['Every column of your file', 'original'],
        ['Only the address and our columns', 'email_only']
      ]
    end
  },

  actions: {
    validate_email: {
      title: 'Validate email',
      subtitle: 'Check one email address',
      description: lambda do |_input, _picklist_label|
        "Validate <span class='provider'>email address</span> in <span class='provider'>email-validation.org</span>"
      end,
      help: lambda do |_input, _picklist_label|
        {
          body: 'Checks one email address and returns its status (valid, invalid, catch_all, unknown, disposable), ' \
                'the reason and the recommended action. Each run of this step is one check: one credit, except ' \
                'unknown results, malformed addresses and sandbox addresses, which are free. A job you repeat ' \
                'or a step Workato retries checks again.',
          learn_more_url: 'https://email-validation.org/docs/test-addresses/',
          learn_more_text: 'Free test addresses'
        }
      end,
      display_priority: 10,
      input_fields: lambda do |_object_definitions, _connection, _config_fields|
        [
          { name: 'email', label: 'Email', optional: false, hint: 'The address to check. Try accepted@sandbox.email-validation.org: test addresses are free.' },
          { name: 'ip_address', label: 'IP address', optional: true, sticky: true, hint: 'Optional IPv4 or IPv6 address the person used when they gave you the address (for example at sign-up). Ignored when it is not a valid IP.' }
        ]
      end,
      execute: lambda do |connection, input, _input_schema, _output_schema|
        email = input['email'].to_s.strip
        error('[invalid_request] Map an email address into Email.') if email.blank?
        body = { 'email' => email }
        ip = input['ip_address'].to_s.strip
        body['ip_address'] = ip if ip.present?
        call('api_request', connection, 'post', '/v1/validate', { 'json' => body })
      end,
      output_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['validation_result']
      end,
      sample_output: lambda do |_connection, _input|
        call('sample_validation_result')
      end
    },

    get_credits: {
      title: 'Get credit balance',
      subtitle: 'Read your credit balance and lots',
      description: lambda do |_input, _picklist_label|
        "Get <span class='provider'>credit balance</span> in <span class='provider'>email-validation.org</span>"
      end,
      help: lambda do |_input, _picklist_label|
        'Reads your credit balance, any debt, pending credits and the lots with their expiry dates. Free.'
      end,
      display_priority: 9,
      input_fields: lambda do |_object_definitions, _connection, _config_fields|
        []
      end,
      execute: lambda do |connection, _input, _input_schema, _output_schema|
        call('api_request', connection, 'get', '/v1/credits', {})
      end,
      output_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['credits']
      end,
      sample_output: lambda do |_connection, _input|
        call('sample_credits')
      end
    },

    create_bulk_job: {
      title: 'Create bulk job',
      subtitle: 'Upload a list of addresses to check',
      description: lambda do |_input, _picklist_label|
        "Create <span class='provider'>bulk job</span> in <span class='provider'>email-validation.org</span>"
      end,
      help: lambda do |_input, _picklist_label|
        'Uploads a list as one bulk job: either addresses (one per line, or separated by commas) or the text of ' \
          'a CSV file. With Start right away on (the default) checking starts after the list is analyzed and ' \
          'credits are held for it. Leave this step out of Workato retries: the API cannot tell a re-sent list ' \
          'from a new one. If it fails with a timeout or a 5xx error, look under Bulk lists in the dashboard ' \
          'before running it again: the job may exist and may already have started. Needs a key with Bulk lists.'
      end,
      bulk: true,
      display_priority: 8,
      input_fields: lambda do |_object_definitions, _connection, _config_fields|
        [
          { name: 'emails', label: 'Email addresses', control_type: 'text-area', optional: true, hint: 'One address per line, or separated by commas; up to 100,000. Join a list of addresses into one text with a formula first. Fill in this or CSV file content.' },
          { name: 'file_content', label: 'CSV file content', control_type: 'text-area', optional: true, hint: 'The text of a CSV or text file, for example the contents a file download step returned. Up to 100 MB; the job history keeps what this step sends (Workato cuts job details past 1 MB).' },
          { name: 'column', label: 'Address column', optional: true, sticky: true, hint: 'For CSV file content: the column that holds the addresses, a 1-based index or the header name. When empty we detect it.' },
          {
            name: 'has_header', label: 'First row is a header', type: 'boolean', control_type: 'checkbox', optional: true,
            sticky: true, hint: 'For CSV file content. When empty we detect it.'
          },
          {
            name: 'start', label: 'Start right away', type: 'boolean', control_type: 'checkbox', optional: true,
            sticky: true, hint: 'Start checking as soon as the list has been analyzed (default). Set to no to review the cost first and use Start bulk job later.'
          },
          { name: 'webhook_endpoint_id', label: 'Webhook endpoint ID', optional: true, sticky: true, hint: 'Id of a webhook endpoint registered in the dashboard, notified when the job finishes.' }
        ]
      end,
      execute: lambda do |connection, input, _input_schema, _output_schema|
        emails = input['emails']
        emails = emails.to_s.split(/[\r\n,]+/) unless emails.is_a?(Array)
        emails = emails.map { |email| email.to_s.strip }.reject(&:blank?)
        file_content = input['file_content'].to_s
        if emails.present? && file_content.strip.present?
          error('[invalid_request] Fill in Email addresses or CSV file content, not both.')
        elsif emails.blank? && file_content.strip.blank?
          error('[invalid_request] Fill in Email addresses or CSV file content.')
        end
        params = {}
        start = call('flag', input['start'])
        params['start'] = start unless start.nil?
        webhook = input['webhook_endpoint_id'].to_s.strip
        params['webhook_endpoint_id'] = webhook if webhook.present?
        if emails.present?
          call('api_request', connection, 'post', '/v1/bulk', { 'params' => params, 'json' => { 'emails' => emails } })
        else
          column = input['column'].to_s.strip
          params['column'] = column if column.present?
          has_header = call('flag', input['has_header'])
          params['has_header'] = has_header unless has_header.nil?
          call('api_request', connection, 'post', '/v1/bulk', { 'params' => params, 'body' => file_content, 'content_type' => 'text/csv' })
        end
      end,
      output_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['bulk_job']
      end,
      sample_output: lambda do |_connection, _input|
        call('sample_bulk_job').merge('status' => 'analyzing')
      end
    },

    start_bulk_job: {
      title: 'Start bulk job',
      subtitle: 'Start checking a list that waits in ready',
      description: lambda do |_input, _picklist_label|
        "Start <span class='provider'>bulk job</span> in <span class='provider'>email-validation.org</span>"
      end,
      help: lambda do |_input, _picklist_label|
        'Starts a job created with Start right away off, or one whose start was refused (for example for missing ' \
          'credits). While the list is still being analyzed it reads the job about once a minute (free) and ' \
          'starts it when the analysis is done, for at most 60 minutes. Safe to run again: starting a started ' \
          'job returns it and never holds credits twice.'
      end,
      display_priority: 7,
      input_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['job_id_input']
      end,
      # A new list is `analyzing` first, and the API answers a start then with 409 "still being analyzed": read the
      # job (free) and wait while it is analyzing, then send the start once. The API starts a job once however often it
      # is asked (a started job is returned as it is), so a rerun never holds credits twice.
      execute: lambda do |connection, input, _input_schema, _output_schema, closure|
        path = call('job_path', input['job_id'], '')
        polls = (closure || {})['polls'].to_i
        job = call('api_request', connection, 'get', path, {})
        if job['status'] != 'analyzing'
          call('api_request', connection, 'post', "#{path}/start", {})
        elsif polls + 1 >= 60
          error("[timeout] Bulk job #{input['job_id'].to_s.strip} is still being analyzed after 60 minutes. Run Start bulk job again, or start it under Bulk lists in the dashboard.")
        else
          reinvoke_after(seconds: 60, continue: { 'polls' => polls + 1 })
        end
      end,
      output_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['bulk_job']
      end,
      sample_output: lambda do |_connection, _input|
        call('sample_bulk_job').merge('status' => 'queued')
      end
    },

    get_bulk_job: {
      title: 'Get bulk job',
      subtitle: 'Read the status and counts of a bulk job',
      description: lambda do |_input, _picklist_label|
        "Get <span class='provider'>bulk job</span> in <span class='provider'>email-validation.org</span>"
      end,
      help: lambda do |_input, _picklist_label|
        'Reads a bulk job: its status, counts per status and credits. Free.'
      end,
      display_priority: 6,
      input_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['job_id_input']
      end,
      execute: lambda do |connection, input, _input_schema, _output_schema|
        call('api_request', connection, 'get', call('job_path', input['job_id'], ''), {})
      end,
      output_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['bulk_job']
      end,
      sample_output: lambda do |_connection, _input|
        call('sample_bulk_job')
      end
    },

    wait_for_bulk_job: {
      title: 'Wait for bulk job to finish',
      subtitle: 'Check a bulk job every minute until it ends',
      description: lambda do |_input, _picklist_label|
        "Wait for <span class='provider'>bulk job</span> in <span class='provider'>email-validation.org</span>"
      end,
      help: lambda do |_input, _picklist_label|
        'Reads the job about once a minute (each read is free) and continues the recipe when the job is completed, ' \
          'failed, cancelled or expired, or waits in ready with an error code (a start that was refused, for ' \
          'example for missing credits: it never moves on by itself). Check Status before downloading results. ' \
          'A job created with Start right away off waits in ready until Start bulk job: start it first.'
      end,
      display_priority: 5,
      input_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['job_id_input'] + [
          {
            name: 'max_wait_minutes', label: 'Wait at most (minutes)', type: 'integer', control_type: 'integer',
            optional: true, sticky: true, hint: 'Default 60, at most 90 (Workato re-runs a multistep action at most 100 times, at least a minute apart). The step fails with [timeout] when the job is still running then; run it again to keep waiting.'
          }
        ]
      end,
      execute: lambda do |connection, input, _input_schema, _output_schema, closure|
        path = call('job_path', input['job_id'], '')
        max_minutes = input['max_wait_minutes'].to_i
        max_minutes = 60 if max_minutes <= 0
        max_minutes = 90 if max_minutes > 90
        polls = (closure || {})['polls'].to_i
        job = call('api_request', connection, 'get', path, {})
        if call('bulk_job_finished', job)
          job
        elsif polls + 1 >= max_minutes
          error("[timeout] Bulk job #{job['id']} is still #{job['status']} after #{max_minutes} minutes. Run Wait for bulk job again, or check it under Bulk lists in the dashboard.")
        else
          reinvoke_after(seconds: 60, continue: { 'polls' => polls + 1 })
        end
      end,
      output_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['bulk_job']
      end,
      sample_output: lambda do |_connection, _input|
        call('sample_bulk_job')
      end
    },

    cancel_bulk_job: {
      title: 'Cancel bulk job',
      subtitle: 'Stop a bulk job that has not finished',
      description: lambda do |_input, _picklist_label|
        "Cancel <span class='provider'>bulk job</span> in <span class='provider'>email-validation.org</span>"
      end,
      help: lambda do |_input, _picklist_label|
        'Cancels a bulk job that has not finished. Needs a key with Bulk lists.'
      end,
      display_priority: 3,
      input_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['job_id_input']
      end,
      execute: lambda do |connection, input, _input_schema, _output_schema|
        call('api_request', connection, 'delete', call('job_path', input['job_id'], ''), {})
      end,
      output_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['bulk_job']
      end,
      sample_output: lambda do |_connection, _input|
        call('sample_bulk_job').merge('status' => 'cancelling', 'finished_at' => nil)
      end
    },

    download_bulk_results: {
      title: 'Download bulk results',
      subtitle: 'Get the result file of a completed bulk job as CSV text',
      description: lambda do |_input, _picklist_label|
        "Download <span class='provider'>bulk results</span> in <span class='provider'>email-validation.org</span>"
      end,
      help: lambda do |_input, _picklist_label|
        'Returns the result file of a completed job as CSV text (UTF-8), your columns followed by ours ' \
          '(ev_status, ev_reason, ev_action and more). Map CSV contents into a file step (for example an upload ' \
          'to cloud storage) or a CSV parser. Free. The whole file passes through this step, so very large ' \
          'lists are better downloaded from the dashboard. A job that is not completed answers [conflict].'
      end,
      display_priority: 4,
      input_fields: lambda do |object_definitions, _connection, _config_fields|
        object_definitions['job_id_input'] + [
          { name: 'filter', label: 'Rows', control_type: 'select', pick_list: 'results_filters', optional: true, sticky: true, hint: 'All rows (default) or the rows of one status.' },
          { name: 'columns', label: 'Columns', control_type: 'select', pick_list: 'results_columns', optional: true, sticky: true, hint: 'Every column of your file (default), or only the address and our columns.' },
          {
            name: 'escape_formulas', label: 'Escape formulas', type: 'boolean', control_type: 'checkbox', optional: true,
            sticky: true, hint: 'Prefix cells from your file that start with =, +, - or @ so spreadsheets do not run them as formulas (default yes).'
          }
        ]
      end,
      execute: lambda do |connection, input, _input_schema, _output_schema|
        path = call('job_path', input['job_id'], '/results')
        params = {}
        filter = input['filter'].to_s.strip
        if filter.present?
          error('[invalid_request] Rows must be all, valid, invalid, catch_all, unknown or disposable.') unless %w[all valid invalid catch_all unknown disposable].include?(filter)
          params['filter'] = filter
        end
        columns = input['columns'].to_s.strip
        if columns.present?
          error('[invalid_request] Columns must be original or email_only.') unless %w[original email_only].include?(columns)
          params['columns'] = columns
        end
        escape = call('flag', input['escape_formulas'])
        params['escape_formulas'] = escape unless escape.nil?
        contents = call('api_request', connection, 'get', path, { 'params' => params, 'accept' => 'csv' })
        { 'job_id' => input['job_id'].to_s.strip, 'contents' => contents }
      end,
      output_fields: lambda do |_object_definitions, _connection, _config_fields|
        [
          { name: 'job_id', label: 'Job ID' },
          { name: 'contents', label: 'CSV contents', hint: 'The result file as CSV text (UTF-8).' }
        ]
      end,
      sample_output: lambda do |_connection, _input|
        {
          'job_id' => 'job_3Fv8QpL2xM7nC1rT9kW4yB',
          'contents' => "email,first_name,ev_status,ev_reason,ev_action\naccepted@sandbox.email-validation.org,Ana,valid,accepted,send\n"
        }
      end
    }
  },

  triggers: {}
}
