class UpdateController < ApiController
  def update
    return render plain: "Unauthorized", status: :unauthorized unless authorized?
    return render plain: "Version not provided", status: :bad_request if params[:version].blank?

    input = UpdateInputDto.new(
      platform: params[:platform],
      name:     params[:name],
      version:  params[:version]
    )

    UpdateService.new.update(input)
    render plain: "Updated"
  rescue ArgumentError => e
    render plain: e.message, status: :bad_request
  rescue => e
    Rails.logger.error("[UpdateController] #{e.class}: #{e.message}\n#{e.backtrace.first(5).join("\n")}")
    render plain: e.message, status: :internal_server_error
  end

  private

  def authorized?
    params[:secret] == ENV.fetch("UPDATE_SECRET", "")
  end
end
