require "grape"
require "ostruct"

class Api::Base < Grape::API
  format :json
  default_format :json
  content_type :json, "application/json"

  helpers do
    def parse_since_param(raw_since)
      return nil if raw_since.blank?

      Time.iso8601(raw_since)
    rescue ArgumentError
      error!({ error: "Invalid since parameter. Use ISO8601 timestamp." }, 400)
    end
  end

  resource :entries do
    desc "Return public entries in all languages",
         attributes: OpenStruct.new(success: nil, produces: nil)
    params do
      optional :since,
               type: String,
               desc: "ISO8601 timestamp. Returns entries updated after this time."
    end
    get do
      since_time = parse_since_param(params[:since])

      entries_scope = Entry.active_entries
      entries_scope = entries_scope.where("updated_at > ?", since_time) if since_time

      entries_scope
        .order(:updated_at, :id)
        .select(
          :id,
          :category,
          :fi,
          :en,
          :sv,
          :no,
          :ru,
          :de,
          :updated_at
        )
    end
  end
end
