#!/usr/bin/ruby
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# frozen_string_literal: true

require 'sinatra'

CCI_SRC = ENV['CCI_SRC'] || '/c/compass-ci'
require "#{CCI_SRC}/src/lib/data_api.rb"

set :bind, '0.0.0.0'
set :port, 10005
set :show_exceptions, false
set :environment, :production

# POST
# eg1:
#   curl -X POST localhost:10005/data_api/es/jobs/_search -H 'Content-Type: application/json' -d '{
#     "query": {"size":10, "sort": [{"start_time": {"order": "desc"}}]},
#     "cci_credentials": {
#       "my_token": "16132550-...",
#       "my_account": "auto-submit"
#     }
#   }'
# Response:
#   - es_result : JSON
post '/data_api/es/:index/_search' do
  request.body.rewind # in case someone already read it
  es_search(params['index'], request.body.read)
end


# POST
# eg1:
#   curl -X POST localhost:10005/data-api/search -H 'Content-Type: application/json' -d '{
#     "index": jobs,
#     "query": {"size":10, "sort": [{"start_time": {"order": "desc"}}]}
#   }'
# Response:
#   - es_result : JSON
post '/data-api/search' do
  request.body.rewind # in case someone already read it
  body = JSON.parse(request.body.read)
  es_search(body['index'], body.to_json)
end

# POST
# eg1:
#   curl -X POST localhost:10005/data_api/_opendistro/_sql -H 'Content-Type: application/json' -d '{
#     "query": "SELECT * FROM jobs WHERE ...",
#     "cci_credentials": {
#       "my_token": "16132550-...",
#       "my_account": "auto-submit"
#     }
#   }'
# Response:
#   - es_result : JSON
post '/data_api/_opendistro/_sql' do
  request.body.rewind # in case someone already read it
  es_opendistro_sql(request.body.read)
end
