# frozen_string_literal: true

module MediaSearch
  module V1
    class API < Grape::API
      version 'v1', using: :path
      helpers do
        def current_user
          @current_user ||= ApiAuthorizeUserRequest.call(request.headers).result
        end

        def authenticate!
          unauthorized! unless current_user
        end

        def unauthorized!
          error!('401 Unauthorized', 401)
        end

        params :pagination do
          optional :page, type: Integer, default: 1, desc: 'Page number to retrieve.'
          optional :per_page, type: Integer, default: 10, desc: 'Items per page. Maximum: 50'
        end
      end

      namespace :users do
        desc 'Authenticate User with login & password and returns a JWT token.'
        params do
          requires :login, type: String, desc: 'User Login.'
          requires :password, type: String, desc: 'User Password.'
        end

        post :auth do
          command = ApiAuthenticateUser.call(params[:login], params[:password])
          command.success? ? { auth_token: command.result } : unauthorized!
        end
      end

      namespace :media do
        before { authenticate! }

        desc 'Return a list of Media.'
        params do
          use :pagination
          # list of all accepted sort param strings
          optional :sort_by, type: String, default: 'by_reception_date', values: %w[by_reception_date by_asc_date by_relevance by_date_created by_asc_created by_random by_n_per_agency], desc: 'Sort order of results.'
          # TODO: what is the format: keyword1,keyword2, ... ?
          optional :keywords, type: String, default: '', desc: 'Search keywords.'
          optional :provider_id, type: Array[Integer], default: [], desc: 'Filtering on Provider Ids'
        end

        get :search do
          command = ApiSearchMediaQuery.call(current_user, params)
          command.success? ? command.result : command.errors
        end

        desc 'Export id & name columns of all providers'
        get :export_providers do
          Provider.all.order(:name).pluck(:name, :id)
        end

        desc 'Return HD Image download link'
        params do
          requires :ids, type: Array, desc: 'MS Picture Ids'
        end
        get :hd_link do
          args = { server_name: current_user.title.server.name,
                   title_name: current_user.title.name,
                   remote_ip: env['REMOTE_ADDR'],
                   login: current_user.login,
                   ids: params[:ids] }
          command = ApiHdDownloadLink.call(args)
          command.success? ? command.result : command.errors
        end
      end
    end
  end
end
